Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument
I'm trying to understand the difference between the two methods below:
def first_append(new_item, a_list=[]):
a_list.append(new_item)
return a_list
def second_append(new_item, a_list=None):
if a_list is None:
a_list = []
a_list.append(new_item)
return a_list
first_append
keeps adding to a_list
when called multiple times, causing it to grow. However, second_append
always returns a list of length 1. What is the difference here?
Examples:
>>> first_append('one')
['one']
>>> first_append('two')
['one', 'two']
>>> second_append('one')
['one']
>>> second_append('two')
['two']