Search code examples
pythonpython-3.xfunctiondel

Deleting an default argument inside function in Python


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.


Solution

  • 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.