0
def f(a, L=[]):
    L.append(a)
    return L

print(f(1))
print(f(2))
print(f(3))

This example is borrowed from https://docs.python.org/3/tutorial/controlflow.html#default-argument-values.

I expected the result to be [1], [2], and [3], respectively, but they were actually [1], [1,2], and [1,2,3].

I thought the argument L is initialized to an empty list every time I call the function f(). Why is the previous result passed to the function f() next time I call it?

user67275
  • 1
  • 9
  • 38
  • 64
  • 2
    Does this answer your question? ["Least Astonishment" and the Mutable Default Argument](https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument) Don't use mulatble default arguments. – buran Feb 12 '22 at 09:25
  • 1
    Also https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments – buran Feb 12 '22 at 09:26

0 Answers0