[Tutor] Question about default values for arguments

Alan Gauld alan.gauld at btinternet.com
Thu Oct 11 18:08:14 CEST 2007


"Roy Chen" <roychenlei at gmail.com> wrote

> def f(a, L=[]):
>    L.append(a)
>    return L

This creates a single list object L used for all calls to f()
that don;t provide an explicit L. Thus each call appends
to the same object.

>
> def g(a, L=None):
>     if L == None:
>         L = []
>     L.append(a)
>     return L

This creates a new L on each invocation of g() where
L is None or not supplied.

> print f(1)
> print f(2)
> print f(3)
> print g(1)
> print g(2)
> print g(3)
>
> The output is:
> [1]
> [1, 2]
> [1, 2, 3]

The same default object returned each time

> [1]
> [2]
> [3]

3 new objects returned.

> I understand that default arguments are evaluated once only, at the
> point of function definition, but I can't wrap my head around how 
> the
> function g() doesn't do the same thing as the function f().

Because it creates a new object at execution not at definition.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list