Please take a gander at this function
with a mutable object list
as a default argument:
def foo(x, items = []):
items.append(x)
return items
foo(1) #returns [1]
foo(2) #returns [1,2]
foo(3) #returns [1,2,3]
I am curious as to why does this happen? I mean I have read that a function's
scope is terminated as soon as it finishes execution, so the items
in the first call must have been destroyed after the first call. I then tried to check if the items
was in global scope.
>>> print(items)
>>> Traceback (most recent call
File "c:\Users\GauriShanker\Desktop\mypython\test.py", line 9, in <module>
print(items)
NameError: name 'items' is not defined.
Turns out it is not. I am curious as to :
- why was not the
items
variable destroyed after every call. As is evident clearly, every successive function call is picking the value of theitems
variable from the last function call. If theitems
variable is not in global scope, where does it live and why? - When I have not explicitly provided the second arguement in function calls, should it not just make
items
equal to[]
as the default value. Isn't the whole point of declaring the default parameters? It does setitems
to[]
only in the first call but not in the second and third call.
Please guide.