I am a beginner to Python. While going over the official introduction https://docs.python.org/2/tutorial/controlflow.html, I couldn't quite understand the last example in section in 4.7.1. Specifically, why does
def f(a, L=None):
if L is None:
L = []
L.append(a)
return L
not share values among subsequent calls when the function is evaluated without explicitly providing the default value for L
?
Suppose I evaluate f(1)
and f(2)
in succession. For the first call, L
is set to None
, the default value, so the if
loop condition is satisfied and L
is set to []
. L
is then modified to [1]
and returned as output. On the second call, L
is still [1]
*, which is not None
, so the if
loop should not be initiated, and I would expect the output to simply be 2
appended to [1]
, i.e. [1,2]
, whereas the output is [2]
.
So * must be false. But when I evaluate print(f(1))
, I get [1]
as output, not None
. Compounding to my confusion is the penultimate example in the same section:
def f(a, L=[]):
L.append(a)
return L
print f(1)
print f(2)
print f(3)
returns
[1]
[1, 2]
[1, 2, 3]
What is going on over here? The website does say default values are only evaluated once, so does the value only carry over when the default value is set to a mutable object, as is the case above with []
? If that is so, I would presume None
is immutable in the first example, and the value of L
that is returned is discarded immediately upon execution and display of the output.