-3

I am intrigued by the output the following code generates. Can anyone explain to me why python prints [1,5] and not just [5] when it executes the function call for the third time, and if it is a feature or a bug in Python?

def funn(arg1, arg2=[]):
    arg2.append(arg1)
    print(arg2)
funn(1)
funn(2, [3, 4])
funn(5)
  • I believe it is because `arg2` is only assigned the default value (empty array) the first time it is called. Then any subsequent calls that do no provide a value will use the same instance that way originally created. So the 3 call will use the array that was created in the first call, which already has `1` appended to it. – musefan Jun 07 '18 at 08:24

1 Answers1

2

There is a nice article about this here. But to better understand, I've made a small modification in your function to better visualize the problem.

def funn(arg1, arg2=[]):
    print(id(arg2))
    arg2.append(arg1)
    print(arg2)
funn(1) # here you will get printed an id of arg2
funn(2, [3, 4]) # here it's a different id of arg2 because it's a new list
funn(5) # here you will see that the id of the arg2 is the same as in the first function call.
Tudor Plugaru
  • 347
  • 2
  • 10