On Sun, Jun 26, 2011 at 7:28 PM, Marc Aymerich <glicer...@gmail.com> wrote:
> 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]

Your problem arises because lists are mutable. Because foo (by
default, initially) points to a given list, every time the function is
called, it uses the same list that foo was first pointed to, if the
default argument value is taken.
The way to fix this is to instead do -

def a(foo=None):
    if foo is None:
        foo = []
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to