Default Argument Inconsistency?

Heiko Wundram heikowu at ceosg.de
Tue Apr 27 05:55:33 EDT 2004


I guess I'll best describe this behavior when commenting directly in the code.

Am Dienstag, 27. April 2004 11:24 schrieb Paul Sweeney:
> def f(a,L=[]):
>     if not L: L=[]

It checks whether not L (in this context, meaning that the list is empty). The 
list is (initialized with []), so the action is triggered. The action creates 
a new empty list, whose reference is now stored in L. The list which is 
constructed as the default argument is unbound from L, but still referenced 
in the function object for f (as the default argument for L, if it isn't 
present).

>     L.append(a)

The append appends an item to the newly created empty list.

>     return L

The append returns the new list.

Hope this sheds light on this behavior. When calling in for the second time, 
the default argument is still empty, a new list is created, etc. The default 
argument thus never changes from being the empty list.

Heiko.




More information about the Python-list mailing list