When do the Augmented Assignment operations behave as in-place operations and when do not?

69 Views Asked by At

I've always known that Python augmented operations always perform in-place operations. But seems like it's not true for every case. When I apply Augmented operations on integers, it's not in place.

    var1 = 1234
    print(id(var1))
    var1 = var1 + 4321
    print(id(var1))

    print()

    var2 = 5678
    print(id(var2))
    var2 += 8765
    print(id(var2))

Output:

140272195234704
140272195234928

140272195234736
140272195234896    

But when I apply it on lists, it's in place.

    var1 = [1, 2]
    print(id(var1))
    var1 = var1 + [3]
    print(id(var1))

    print()

    var2 = [5, 6]
    print(id(var2))
    var2 += [7]
    print(id(var2))

Output:

140461597772992
140461597413184

140461597412480
140461597412480

My question is, when does it behave as an in-place operation and when does it not? And why?

2

There are 2 best solutions below

3
On

When you run var1 = var1 + [3], Python first performs the operation on the right, and then assigns it to the variable on the left. It creates a completely new list with the results of the value on the right, and then then assigns it to the left. It makes sense that the old list and the new list are different. In fact, if you ran:

var1 = [1, 2]
var2 = var1
var1 = var1 + [3]

That var2 will have the same id as var1 after the second instruction, and that var2 will continue to have that same id after the third instruction, while the id of var changes.

On the other hand, var2 += [7] is an indication that it is okay to reuse the same space. And += on lists, in most cases, does reuse the same space.

2
On

With integers, you're replacing one integer with another in both cases because integers are immutable. Since in both cases, you're talking about a new object getting assigned to the variable, the id of what the variable is pointing to changes in both cases.

In the first list case, you're effectively doing the same thing, replacing one list with another because that's what the + operator does...it combines its two operand lists and returns a new list.

But in the += case, you're not changing which list var2 is pointing to, but rather just manipulating the list that it is pointing to. Lists are mutable objects that can be modified. The += operator acts like the list's extend method, appending the items in the supplied list onto the existing list. Because the list that var2 is pointing to doesn't change, the id doesn't change either.