Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument
I recently met a problem in Python. Code:
def f(a, L=[]):
L.append(a)
return L
print f(1)
print f(2)
print f(3)
the output would be
[1]
[1, 2]
[1, 2, 3]
but why the value in the local list: L in the function f remains unchanged? Because L is a local variable, I think the output should be:
[1]
[2]
[3]
I tried another way to implement this function: Code:
def f(a, L=None):
if L is None:
L = []
L.append(a)
return L
This time, the output is:
[1]
[2]
[3]
I just don't understand why... Does anyone have some ideas? many thanks.