newbie question

Steven Majewski sdm7g at Virginia.EDU
Sun Jan 13 10:30:45 EST 2002


On Sun, 13 Jan 2002, rihad wrote:

>
> def f(n, x = []):
>    # some code
>
> Even if I don't modify x inside f(), is it guaranteed that x will
> always be [], that is, the empty list [] will never be shared with
> some unrelated reference, which could modify it, and thus affect what
> x binds to?

No. (If I understand what you're asking.)
The list that x is bound to by default isn't shared with some
unrelated reference, but the same reference is shared by every
invocation of f():

>>> def f( n, x=[] ):
...     x.append(n)
...     print x
...
>>> f(3)
[3]
>>> f(4)
[3, 4]
>>> f(5)
[3, 4, 5]

And of course, if you pass value for x in the function call, that
reference is shared and modified.

>>> a = [1,2,3]
>>> f(4,a)
[1, 2, 3, 4]
>>> a
[1, 2, 3, 4]


The typical idiom, if you want a new empty list for each invocation
using the default args is:

>>> def f(n, x=None):
...     if x == None: x = []
...     x.append(n)
...     print x
...
>>> f(1)
[1]
>>> f(2)
[2]


Although the function body may be executed many times,
the *definition* of the function happens only once, so the default
arglist is only evaluated once (and thus is the same object on
every invocation.)


See: <http://www.python.org/doc/FAQ.html#6.25>

-- Steve Majewski






More information about the Python-list mailing list