16
votes

consider the following code:

>>> x = y = [1, 2, 3, 4]
>>> x += [4]
>>> x
[1, 2, 3, 4, 4]
>>> y
[1, 2, 3, 4, 4]

and then consider this:

>>> x = y = [1, 2, 3, 4]
>>> x = x + [4]
>>> x
[1, 2, 3, 4, 4]
>>> y
[1, 2, 3, 4]

Why is there a difference these two?

(And yes, I tried searching for this).

3
What is interesting about your last statement, is that this functionality is actually explained in the python docs: docs.python.org/reference/datamodel.html#object.__add__ (from searching about those terms) - jdi
@jdl: Yes I admit that I overlooked that. - S Singh

3 Answers

32
votes

__iadd__ mutates the list, whereas __add__ returns a new list, as demonstrated.

An expression of x += y first tries to call __iadd__ and, failing that, calls __add__ followed an assignment (see Sven's comment for a minor correction). Since list has __iadd__ then it does this little bit 'o mutation magic.

4
votes

The first mutates the list, and the second rebinds the name.

1
votes

1)'+=' calls in-place add i.e iadd method. This method takes two parameters, but makes the change in-place, modifying the contents of the first parameter (i.e x is modified). Since both x and y point to same Pyobject they both are same.

2)Whereas x = x + [4] calls the add mehtod(x.add([4])) and instead of changing or adding values in-place it creates a new list to which a points to now and y still pointing to the old_list.