-1

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']
Community
  • 1
  • 1
Rob Volgman
  • 2,104
  • 3
  • 18
  • 28

1 Answers1

0

Function second_append always creates a new local list for you each time it is called.

Levon
  • 138,105
  • 33
  • 200
  • 191