The following code
def f(x,l=[]):
for i in range(x):
l.append(i*i)
print(l)
f(2)
f(3)
outputs
[0, 1]
[0, 1, 0, 1, 4]
And not the trivial
[0, 1]
[0, 1, 4]
This means that the named argument l
is actually a single consistent variable THAT DOESN'T GET RESET on new calls to f
.
This is obviously not a bug, and is by design.
My question is why is this the desired behavior? To me it seems more confusing than helpful, and this would make me never want to use default values that are not immutable.