problem calling functions with default arguments

Dietmar Lang dietmar at wohnheim.fh-wedel.de
Wed Aug 15 14:47:21 EDT 2001


Russell E. Owen wrote:
> def atest(alist = []):
>   print "alist =", alist
>   alist.append("test")
>
> atest()
> atest()
> atest()
> 
> I was expecting that alist would be empty every time it is printed.
> However, when I run the code I see:
> 
> alist = []
> alist = ['test']
> alist = ['test', 'test']

It has to do with the fact that we have just one list object here: The
one created when atest() was first executed. It seems that Python
doesn't create a new list every time, so it keeps growing with each
append.

You can though, move the default value into the function body. For
example:

def atest(alist = None):
    if alist is None:
        alist = []
    print 'alist =', alist
    alist.append('test')

Now it should work. Thanks to my O'Reilly book for pointing that one out
on me before I had to come face to face with it. :-)

Kudos, Dietmar



More information about the Python-list mailing list