[Tutor] Question about default values for arguments
Roy Chen
roychenlei at gmail.com
Thu Oct 11 17:27:05 CEST 2007
Hi everyone, been looking at the following functions, but can't
figure out how they work.
def f(a, L=[]):
L.append(a)
return L
def g(a, L=None):
if L == None:
L = []
L.append(a)
return L
print f(1)
print f(2)
print f(3)
print g(1)
print g(2)
print g(3)
The output is:
[1]
[1, 2]
[1, 2, 3]
[1]
[2]
[3]
I understand that default arguments are evaluated once only, at the
point of function definition, but I can't wrap my head around how the
function g() doesn't do the same thing as the function f().
Any help would be most appreciated, thanks.
More information about the Tutor
mailing list