default arguments newbie question
Victor Muslin
victor at prodigy.net
Wed Jan 10 16:07:25 EST 2001
This behavior of the default list argument seems to be somewhat
counter-intuitive:
>>> def f(l=[]):
... l.append(1)
... print 'id=%d %s' % (id(l), l)
...
>>> f()
id=8369232 [1]
>>> f()
id=8369232 [1, 1]
>>> f()
id=8369232 [1, 1, 1]
>>> f([2])
id=8368384 [2, 1]
>>> f()
id=8369232 [1, 1, 1, 1]
>>>
If I want a function to print "[1]" every time it is called with no
arguments, do I have to do something like:
def f(l=None):
if l == None:
print [1]
else:
print l.append(1)
What's the acceptable Python idiom for this?
More information about the Python-list
mailing list