Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why 'x += y' is not always the same as 'x = x + y' in Python (2.7)? [duplicate]

Tags:

python

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
like image 693
matiascelasco Avatar asked Dec 24 '22 15:12

matiascelasco


1 Answers

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.

like image 146
matiascelasco Avatar answered May 10 '23 13:05

matiascelasco