Optional parameters in functions and their mutable default values
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
Default parameters are, quite intuitively, somewhat like member variables on the function object.
Default parameter values are evaluated when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that same “pre-computed” value is used for each call. This is especially important to understand when a default parameter is a mutable object, such as a list or a dictionary: if the function modifies the object (e.g. by appending an item to a list), the default value is in effect modified.
http://docs.python.org/reference/compound_stmts.html#function
Lists are a mutable objects; you can change their contents. The correct way to get a default list (or dictionary, or set) is to create it at run time instead, inside the function:
def good_append(new_item, a_list=None):
if a_list is None:
a_list = []
a_list.append(new_item)
return a_list