Possible Duplicate:
What does plus equals (+=) do in Python?
I noticed a strange problem:
l1 = ['1', '2', '3']
l2 = l1
item = l2.pop(0)
# the pop operation will effect l1
print l1
l2 = l2 + [item]
# why "l2 = l2 + [item]" does't effect l1 while "l2 += [item]" does.
print l2
print l1
The output is:
['2', '3']
['2', '3', '1']
['2', '3']
But if i change l2 = l2 + [item] into l2 += [item], the output will be:
['2', '3']
['2', '3', '1']
['2', '3', '1']
+and+=are different operators woth different internal meaning as described here.l2 = l1 + xcallsl2 = l1.__add__(x), if that doesn’t work it callsx.__radd__(l1). Both should return a new object forming the result of the operation, independent from the old one, thus not affectingl1.l2 += xcallsl2 = l2.__iadd__(x)(“augmented assignment”), and only if this doesn’t work, falls back tol2 = l2 + xas described above.With numbers, both are the same, because they are immutable and thus cannot be modified with
+=, while on lists,+returns a new object while+=modifies the left hand side one.As the object behind
l2is modified andl1refers the same object, you notice the change onl1as well.