0

I've just ran into a python code that I cannot explain its behavior. The lines are the followings:

def f(a, list=[]):
  for i in range(a):
    list.append(i*i)
  print(list)
f(3)
f(2, [1,2])
f(2)

The output of the calls are:

[0, 1, 4]
[1, 2, 0, 1]
[0, 1, 4, 0, 1]

Why the first list instance is not destroyed and the third call simply returns [0, 1]? What python rule am I missing?

thanks

tul1
  • 412
  • 1
  • 6
  • 22
  • 1
    `"What python rule am I missing?"` the one that says "never-ever use a mutable default argument unless you really know what you are doing" – DeepSpace Jan 21 '20 at 18:27
  • your first call is assigning `list` a value of `[0, 1, 4]`, basically. – segFault Jan 21 '20 at 18:28

1 Answers1

3

You've got bit by an old python gotcha. When using default arguments you should make sure that you are only using immutable values, unless you explicitly want to re-use these objects.

When the function is being defined the list is being created in memory, you append to this list, and when you call the default again it is referencing the same list.

The following would be a best practice way to do what you were attempting to do.

def f(a, list=None):
  if list is None:
    list = []
  for i in range(a):
    list.append(i*i)
  print(list)

Here's an article explaining it better than I can. https://docs.python-guide.org/writing/gotchas/

OsmosisJonesLoL
  • 244
  • 1
  • 4