def foo(val, arr=[]):
arr.append(val)
return arr
print(foo(1)) ---> outputs [1]
print(foo(2)) ---> outputs [1, 2]
Above happens because the default value (an empty list) was evaluated once, when the function was compiled, then re-used on every call to the function. If this is the case then I am not able to understand output of below python code
def f(x,l=[]):
for i in range(x):
l.append(i*i)
print(l)
f(2)
f(3,[3,2,1])
f(3)
#This outputs below
[0, 1]
[3, 2, 1, 0, 1, 4]
[0, 1, 0, 1, 4]
Here in second call f(), list has been changed to [3, 2, 1, 0, 1, 4]
but in the third call to f() uses list created in first call f() i.e. [0, 1]
I am unable to understand how third call is not using list crated during 2nd f() call.