David Isaac wrote:
> As a Python newbie I found this behavior quite surprising.

It can be even more surprising if a default value is mutable:

>>> def foo(a, b=[]):
...     b.append(a)
...     return b

>>> foo(3,[1,2])
[1, 2, 3]

>>> foo('c',['a','b'])
['a', 'b', 'c']

>>> foo(1)
[1]

So far, everything is behaving much as you'd expect, but then:

>>> foo(2)
[1, 2]

>>> foo(3)
[1, 2, 3]

The parameter is bound to the list at creation time and, being mutable,
is modifiable each time the function is called.

This can be avoided by modifying your function slightly:

>>> foo(3, [1,2])
[1, 2, 3]

>>> foo('c', ['a','b'])
['a', 'b', 'c']

>>> foo(1)
[1]

>>> foo(2)
[2]

>>> foo(3)
[3]

-alex23

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to