[Tutor] newbie question about default arguments
Pujo Aji
ajikoe at gmail.com
Wed Mar 29 18:33:41 CEST 2006
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 <jadams at iastate.edu> wrote:
>
> Hi all,
> I was going through the tutorial at http://docs.python.org/tut/node6.htmlwhen 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 at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060329/f968655d/attachment.htm
More information about the Tutor
mailing list