What is a function parameter =[] for?
Steven D'Aprano
steve at pearwood.info
Thu Nov 19 06:38:12 EST 2015
On Thu, 19 Nov 2015 11:34 am, fl wrote:
> This is my new
> question: What does 'del' do? It does not look like a thorough list
> deletion from the effect.
Of course not. Did you Read The Fine Manual? Or at least use the interactive
help function? At the Python prompt, enter:
help("del")
and you will see an explanation which includes this:
Deletion of a name removes the binding of that name from
the local or global namespace, depending on whether the
name occurs in a ``global`` statement in the same code
block. If the name is unbound, a ``NameError`` exception
will be raised.
Let us try it with the interactive interpreter:
If the name "x" doesn't exist, and you try to delete it, you get an error:
py> del x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
If "x" does exist, and you delete it, the name no longer exists:
py> x = 42
py> print(x)
42
py> del x
py> print(x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
So "del" deletes **names**.
What happens after the name is deleted? Then the garbage collector may run,
and destroy the object that was bound to the name, reclaiming the memory
used. But **only** if the object is safe to destroy, otherwise that would
lead to segmentation faults and memory corruption.
Here we have ONE object with TWO names:
py> a = [1, 2, 3, 4]
py> b = a
py> b.append(999)
py> print(a)
[1, 2, 3, 4, 999]
If we delete one of those names, the other name keeps the list alive:
py> del a
py> print(b)
[1, 2, 3, 4, 999]
--
Steven
More information about the Python-list
mailing list