I always assumed that
x += y
was just a shortcut for
x = x + y
But it seems that's not the case for lists:
x = []
x2 = x
print x is x2
True
x += [2]
print x is x2
True
x = x + [2]
print x is x2
False
This happens because x += y is not just a shortcut of x = x + y.
There is a Python magic method named __iadd__ that can replace the default behavior of += when the left-value of the operator is an object which belongs to the class we are defining.
So, it seems that the Python built-in type list implements __iadd__ as follows:
def __iadd__(self, other):
for x in other:
self.append(x)
This way, since the default behavior of +=
is been avoided, no new list is created and that's why x
points to the same object after x += [2]
but no after x = x + [2]
. In the later, a new list is created and assigned to the variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With