Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument
Consider the following function:
def foo(L = []):
L.append(1)
print L
Each time I call foo it will print a new list with more elements than previous time, e.g:
>>> foo()
[1]
>>> foo()
[1, 1]
>>> foo()
[1, 1, 1]
Now consider the following function:
def goo(a = 0):
a += 1
print a
When invoking it several times, we get the following picture:
>>> goo()
1
>>> goo()
1
>>> goo()
1
i.e. it does not print a larger value with every call.
What is the reason behind such seemingly inconsistent behavior?
Also, how is it possible to justify the counter-intuitive behavior in the first example, why does the function retain state between calls?