def f(a, L=None):Why the output for the code:
1. if L is None:
2. L = []
3. L.append(a)
4. return L
f(1)is:
f(2)
f(3)
[1]?????????
[2]
[3]
L=Noneis executed only once, I thought that the line 1 was also executed once, since the line 2 makes the L value to be different of None.
It's not executed only once. The default value is evaluated once, but
the L is assigned every time. The same in the example above with 'def
f(a, L=[])' -- the value is assigned to L every time, but it's the
same object. Try modifying it like this to convince yourself it's the
same object:
def f(a, L=[]):
print id(L)
L.append(a)
return L
when the function f is executed, the default argument None is evaluated
once,and assigned to
the local variable L. But the if conditional statement makes L lose the
reference to the object None.By contrast, in the code presented by
zavandi, L will always reference the object occuping the memory slot
which was occupied by the object [].So,if you run the function call
f(1),f(2),f(3),the result will be:
[1],[1,2],[1,2,3]
Here, when the f(1) is executed, L references the memory slot occupied
by the object [], and later in-place change still makes L reference the
that same memory slot,however the contents change to [1].when the f(2)
is executed, L still references the object occuping the memory slot
which was occupied by the object [1],so the result difference takes
place.