Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument
List extending strange behaviour
Pyramid traversal view lookup using method names
Let’s say I have this function:
def a(b=[]):
b += [1]
print b
Calling it yields this result:
>>> a()
[1]
>>> a()
[1, 1]
>>> a()
[1, 1, 1]
When I change b += [1] to b = b + [1], the behavior of the function changes:
>>> a()
[1]
>>> a()
[1]
>>> a()
[1]
How does b = b + [1] differ from b += [1]? Why does this happen?
In Python there is no guarantee that
a += bdoes the same thing asa = a + b.For lists,
someList += otherListmodifiessomeListin place, basically equivalent tosomeList.extend(otherList), and then rebinds the namesomeListto that same list.someList = someList + otherList, on the other hand, constructs a new list by concatenating the two lists, and binds the namesomeListto that new list.This means that, with
+=, the name winds up pointing to the same object it already was pointing to, while with+, it points to a new object. Since function defaults are only evaluated once (see this much-cited question), this means that with+=the operations pile up because they all modify the same original object (the default argument).