Probably many people know an example:

def foo(a=[]): a.append(1) print (a) foo() foo() foo() 

which issues to print:

 [1] [1, 1] [1, 1, 1] >>> 

I expected to see three identical outputs -

 [1] [1] [1] 

Can you explain the reason for this behavior?
Does the function really store its objects between calls?

Marked as a duplicate by the participants Sergey Gornostaev , 0xdb , aleksandr barakin , AK , Kosta B. 9 Dec '18 at 11:26 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

1 answer 1

The point is that the default argument value is calculated only once - when a function is declared and subsequently this particular object is used for each call. If this object changes for some reason, then at the next function calls the new value will be used.

That is, in other words, recording

def foo(a=[]):

It means not at all "With every function call the argument will be an empty list", but "With every call the argument will be this particular list here, which is still empty, but it may well not be empty in the future."

It is for this reason that it is highly not recommended to take mutable objects as arguments by default.