0

I opened my python interpreter, coded up and ran the following function.

>>> def crazy_function(my_list=[]):
...     my_list.append(0)
...     return my_list
... 
>>> crazy_function()
[0]
>>> crazy_function()
[0, 0]
>>> crazy_function()
[0, 0, 0]
>>> crazy_function()
[0, 0, 0, 0]
>>> crazy_function()
[0, 0, 0, 0, 0]
>>> crazy_function()
[0, 0, 0, 0, 0, 0]
>>> crazy_function()
[0, 0, 0, 0, 0, 0, 0]
>>> 

What is going on? Why does the list returned by the function keep getting longer the more I call the function? Shouldn't a new local list be created every time the function is called?

dangerChihuahua007
  • 20,299
  • 35
  • 117
  • 206

1 Answers1

2

It is a common error to assign mutable objects to a function argument's default value. Quoting the documentation:

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 the 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. This is generally not what was intended.

wRAR
  • 25,009
  • 4
  • 84
  • 97