Optional parameters in functions and their mutable default values

Oscar Mederos picture Oscar Mederos · Jun 22, 2011 · Viewed 51.9k times · Source

Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument

I'm kind of confused about how optional parameters work in Python functions/methods.

I have the following code block:

>>> def F(a, b=[]):
...     b.append(a)
...     return b
...
>>> F(0)
[0]
>>> F(1)
[0, 1]
>>>

Why F(1) returns [0, 1] and not [1]?

I mean, what is happening inside?

Answer

Ben Hayden picture Ben Hayden · Jun 22, 2011

Good doc from PyCon a couple years back - Default parameter values explained. But basically, since lists are mutable objects, and keyword arguments are evaluated at function definition time, every time you call the function, you get the same default value.

The right way to do this would be:

def F(a, b=None):
    if b is None:
        b = []
    b.append(a)
    return b