Hello Josh,

you wrote a different problem. The tutorial should be like this:

Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls:

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

print f(1)
print f(2)
print f(3)

This will print

[1]
[1, 2]
[1, 2, 3]

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

Look the second example use None instead of []

To explain more detail let's create an example :

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

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

def main():
    m = f2(3)
    print m     # produce [3]
    m = f2(4)
    print m     # produce [4]
   
    # ----------------

    m = f1(3)
    print m # produce[3]
    m = f1(4)
    print m # produce[3,4]

    pass

in f1 : when we don't put the second argument the L=[] is created only once. The second input in f1 will be accumulated.

in f2: when we don't put the second argument L is given a None value. Inside this function if L is None then L = [] this will always make L = [] that's way no accumulation happened.

Hope this help.
pujo




On 3/29/06, Josh Adams <[EMAIL PROTECTED]> wrote:
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


_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to