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 += y
first tries to call__iadd__
and, failing that, calls__add__
followed an assignment (see Sven's comment for a minor correction). Sincelist
has__iadd__
then it does this little bit 'o mutation magic.The first mutates the list, and the second rebinds the name.