Default value for optional parameters unexpected behaviour?

Marc Aymerich glicerinu at gmail.com
Sun Jun 26 14:28:30 EDT 2011


Hi,
I'm trying to define a function that has an optional parameter which
should be an empty list whenever it isn't given. However, it takes as
value the same value as the last time the function was executed. What
is the reason of this behaviour? How does python deal with default
values (i.e. when are they assigned/created)?

Thanks :)

>>> def a(foo=[]):
...  foo.append(1)
...  print foo
...
>>> a()
[1]
>>> a()
[1, 1]
>>> a()
[1, 1, 1]
>>> a()
[1, 1, 1, 1]
>>> a()
[1, 1, 1, 1, 1]
>>> a()
[1, 1, 1, 1, 1, 1]



More information about the Python-list mailing list