First page Back Continue Last page Overview Graphics

Lists as Default Parameters

>>> def spammer(bag=[]):

... bag.append("spam")

... return bag

...

>>> spammer()

['spam']

>>> spammer()

['spam', 'spam']

>>> spammer()

['spam', 'spam', 'spam']

>>>

f is called without an argument for the optional parameter.

The first time the optional parameter is used, but not the second time!

Explanation: The default values get assigned to the function when the function is defined, not when the function is called.


Notes:

>>> def a():

... print "a executed"

... return []

...

>>>

>>> def b(x=a()):

... x.append(5)

... print x

...

a executed

>>> b()

[5]

>>> b()

[5, 5]