[Tutor] newbie question about default arguments

Josh Adams jadams at iastate.edu
Wed Mar 29 17:20:06 CEST 2006


Hi all,
I was going through the tutorial at http://docs.python.org/tut/node6.html when I
came to the bit about default arguments with this code:

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]

>From the postings here, I think I understand that this occurs because L is only
initialized when f is first run.  However, this code gives some different results:

def f2(a, L=[]):
     if L == []:
             L = []
     L.append(a)
     return L

print f2(1)
print f2(2)
print f2(3)

returns:
[1]
[2]
[3]

I'm not too clear on why this doesn't return the same results as the first.  Can
someone enlighten me?

Thanks,
Josh




More information about the Tutor mailing list