Default Argument Inconsistency?

Diez B. Roggisch deetsNOSPAM at web.de
Tue Apr 27 05:36:46 EDT 2004


Paul Sweeney wrote:

> The python tutorial gives the following example to demonstrate the fact
> that default args are only evaluated once:
> 
> def f(a,L=[]):
>     L.append(a)
>     return L
> 
> print f(1),f(2),f(3)
> [1] [1,2] [1,2,3]
> 
> now I'm confident I understand this, but I do not understand how changing
> to the following (whatever the merits of so doing, it was an accidental
> typo)
> results in the output displayed:
> 
> def f(a,L=[]):
>     if not L: L=[]
>     L.append(a)
>     return L
> 
>>>> print f(1),f(2),f(3)
> [1] [2] [3]
> 
> surely on second entry to f, L == [1], so the "if not L:" should not
> fire?!

No, its not. As [] is logically false, the 

if not L: L = []

rebinds L with a fresh list. So the append is made to that list, not to the
one L is bound to as default argument.


-- 
Regards,

Diez B. Roggisch



More information about the Python-list mailing list