I know this has been answered in highly active 'least astonishment' question, I modified code snippet slightly but still don't understand why it produces new empty list and adds 1 to it..
def foo(var=[]):
if len(var) == 0:
var = []
print(var)
var.append(1)
return var
print(foo())
print(foo())
outputs:
[]
[1]
[]
[1]
My expected logic of this python snippet:
on the first call of foo(), var is initialized to empty list and indeed - evaluated at definition of foo ONCE - as the popular question answered.
That if clause check should not be entered at all - because var is initialized only once, on the 2nd call foo() it should simply skip it and add 1 to var = [ 1 ] thus making the result [1,1] after the 2nd call.
But it does still go to if clause and init var to [] every time.. why?
However, if I remove the if clause:
def foo(var=[]):
print(var)
var.append(1)
return var
print(foo())
print(foo())
It does append "1" to var every time and var grows:
[1]
[1,1]
So the if clause is entered and checked for validity.. confused about the execution..