functions, list, default parameters

Chris Rebert clp2 at rebertia.com
Thu Oct 21 17:51:02 EDT 2010


On Thu, Oct 21, 2010 at 2:36 PM, Sean Choi <gnemnk at gmail.com> wrote:
> I found two similar questions in the mailing list, but I didn't understand
> the explanations.
> I ran this code on Ubuntu 10.04 with Python 2.6.5.
> Why do the functions g and gggg behave differently? If calls gggg(3) and
> g(3) both exit their functions in the same state, why do they not enter in
> the same state when I call gggg(4) and g(4)?
>
> # ---------------------------------------------------------------------- my
> code:
> def gggg(a, L=[]):

This is a common newbie stumbling-block: Don't use lists (or anything
mutable) as default argument values (in this case, for L); a new list
is *not* created for every function invocation, they'll all share the
*exact same list object*. Use None and then create a fresh list (or
what have you) in the function body. See
http://effbot.org/pyfaq/why-are-default-values-shared-between-objects.htm

>     print "enter function"
>     print "a = ", a, "and L = ", L
>     if L == []:
>         print "hey, L is empty"
>         L = []

The previous line is why the two functions' behaviors differ (g()
lacks this line). Read the above FAQ, and then carefully trace through
the execution of the functions; the difference will then be clear.

Cheers,
Chris
--
http://blog.rebertia.com

>     L.append(a)
>     print "after append, L = ", L
>     return L

> def g(a, L=[]):
>     print "enter function"
>     print "a = ", a, "and L = ", L
>     if L == []:
>         print "hey, L is empty"
>     L.append(a)
>     print "after append, L = ", L
>     return L



More information about the Python-list mailing list