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?
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:That
var2
will have the same id asvar1
after the second instruction, and thatvar2
will continue to have that same id after the third instruction, while the id ofvar
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.