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).
__iadd__mutates the list, whereas__add__returns a new list, as demonstrated.An expression of
x += yfirst tries to call__iadd__and, failing that, calls__add__followed an assignment (see Sven’s comment for a minor correction). Sincelisthas__iadd__then it does this little bit of mutation magic.