Reputation: 49
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.
Upvotes: 1
Views: 1200
Reputation: 4446
First gotcha in the list http://docs.python-guide.org/en/latest/writing/gotchas/
The list is only created once, so if you modify it then that modified version is used next time.
In the second call f(3, [3,2,1])
; it isn't using the default list, it's using the one supplied by you.
So when you call a third time you're using the default list which was only modified by the first call.
as an example, looking up the memory addess for each object using id:
def foo(a=[]):
print id(a)
foo() #140378224732136
foo([]) #140378224687944
foo() #140378224732136
Upvotes: 3