Reputation: 23
I have tried the following in the console:
>>> def f(l=[]):
... l.append(1)
... print(l)
... del l
...
>>> f()
[1]
>>> f()
[1, 1]
What I don't understand is how the interpreter is still able to find the same list l
after the delete instruction.
From the documentation l=[]
should be evaluated only once.
Upvotes: 2
Views: 492
Reputation: 86
To delete a element for the list,del l[:]
should be used.If u use just l
the list will remain itself.
def f(l=[]):
l.append(1)
print(l)
del l[:]
print(l)
>>> f()
[1] #element in the list
[] #list after deletion of the element
>>> f()
[1]
[]
>>> f()
[1]
[]
Upvotes: 0
Reputation: 59103
The variable is not the object. Each time the function is called, the local variable l
is created and (if necessary) set to the default value.
The object []
, which is the default value for l
, is created when the function is defined, but the variable l
is created each time the function runs.
Upvotes: 4