Some strange behaviours of default arguments

Tim Hochberg tim.hochberg at ieee.org
Tue Oct 31 14:26:22 EST 2000


"June Kim" <junaftnoon at nospamplzyahoo.com> writes:

> def add(a, list=[]):
>     list.append(a)
>     print list
[SNIP] 
> 
> >>> add(3)
> [3]
> >>> add(5)
> [3,5]
> 
> Why is the local variable "list"  NOT initialized with the default
> value every time I call it? Can anyone gimme some, if any,
> reasonable explanation?

Does, "because that's the way it works" count? Default arguments are
initialized once when the function definition is evaluated. This means
that one has to be careful when using mutable objects such as lists as
default arguments. The standard idiom for doing what you want is:


def add(a, list=None):
   if list is None:
	list = []
   list.append(a)
   print list


-tim






More information about the Python-list mailing list