0

I have some trouble understanding the output of this code.

def func(a,L = []):
    L.append(a)
    return(L)
print(func(1),func(3))

The output is [1,3][1,3] It seems that each time it takes all the arguments from all the function calls each time a function is called. Does it happen due to same function being called in the same line? How does it work?

  • This has to be Python's most infamous gotcha xD - answer is in the dup. – bruno desthuilliers Apr 21 '20 at 10:32
  • In this case it occurs since they are all in the same line. If you had `print(fun(1)); print(fun(2))` the output would be [1] and [1, 3]. When print evaluates its arguments its is left with print(L, L)-since fund returns L. Since the last state of L is [1, 3], [1, 3] is printed twice. See [Least Astonishment and Mutable Default Value](https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument) for why the default argument keeps getting updated. – DarrylG Apr 21 '20 at 10:49
  • Thanks a lot @brunodesthuilliers and DarrylG . I get it now. Much appreciated. – samtrip Apr 21 '20 at 17:29

0 Answers0