Important warning: The default value is evaluated only once
…
If you don’t want the default to be
shared between subsequent calls, you
can write the function like this
instead:
def f(a, L=None):
if L is None:
L = []
L.append(a)
return L
I still was expecting:
print f(1) # [1]
print f(2) # [1,2]
print f(3) # [1,2,3]
I reason:
The default value (L=None) was executed for f(1) which helped L point to a new empty list in the fn body. However on successive calls, L=None was not executed; so L still points to the list which already has 1 in it now, and subsequent calls are simply appending more elements to it thereby sharing L.
Where am I thinking incorrectly?
UPDATE
def f(a, L=[]):
L.append(a)
return L
Does L here point to an empty list created in heap or stack?
Lis the name of an argument, but it is also a local variable. Rebinding it rebinds the local variable, but does not change the default argument.UPDATE EDIT:
Python doesn’t have “heap” and “stack” in the same manner as C; all it has are objects, and references to those objects. Your function call returns a reference to the same list that was created as the default value for the
Largument of theffunction, and any operation that mutates it will mutate the value of the default argument.