2

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.

2
  • 2
    Each time the function is called the local variable l is created and set to the value of the default argument. The default argument's value is created on function definition, but the variable l is created each time the function runs. Commented Aug 19, 2020 at 12:42
  • 2
    del of a local variable, right at the end of a function, is NEVER going to have any effect whatsoever. It's exactly what's going to happen to the variable anyway. Commented Aug 19, 2020 at 13:26

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Note that if the goal is to clear the contents of the list, del l[:] would do that; l would remain bound to the list (being unbound when the function returns immediately thereafter as normal), but the list itself would have its contents deleted so it's clear for the next call.
Thanks, actually the goal was just understanding what happens with del for a default function argument since I did not find anything about that in the internet.
0

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]
[]

1 Comment

Welcome to Stack Overflow and thanks for your contribution. Unfortunately your code is not indented correctly. See Markdown Editing Help to learn how to format it correctly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.