Why does this:
del a[:]
delete all entries in the list a
?
As far as I understand, a[:]
returns a copy of a
. So shouldn't del a[:]
delete the copy of a
?
del
is a special statement that will check the original value and delete it using the given slice.
It calls __delitem__
on the object and the object itself handles the deletion.
If you're curious regarding the operation happening under the hood, you're welcome to implement the following class and use the del
statement with different slices or key references:
class A:
def __delitem__(self, key):
print(key)
The test in the interpreter:
>>> a = A()
>>> del a[:]
slice(None, None, None)
>>> del a[2]
2
>>> del a["test"]
test