del
StatementThe del
statement also can be used to remove elements from a list and to delete variables from the interactive session. You can remove the element at any valid index or the element(s) from any valid slice.
Let’s create a list, then use del
to remove its last element:
In [1]: numbers = list(range(0, 10))
In [2]: numbers
Out[2]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [3]: del numbers[-1]
In [4]: numbers
Out[4]: [0, 1, 2, 3, 4, 5, 6, 7, 8]
The following deletes the list’s first two elements:
In [5]: del numbers[0:2]
In [6]: numbers
Out[6]: [2, 3, 4, 5, 6, 7, 8]
The following uses a step in the slice to delete every other element from the entire list:
In [7]: del numbers[::2]
In [8]: numbers
Out[8]: [3, 5, 7]
The following code deletes all of the list’s elements:
In [9]: del numbers[:]
In [10]: numbers
Out[10]: []
The del
statement can delete any variable. Let’s delete numbers
from the interactive session, then attempt to display the variable’s value, causing a NameError
:
In [11]: del numbers
In [12]: numbers
-------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-12-426f8401232b> in <module>()
----> 1 numbers
NameError: name 'numbers' is not defined
(Fill-In) Given a list numbers
containing 1 through 10, del
numbers[-2]
removes the value _____ from the list.
Answer: 9.
(IPython Session) Create a list called numbers
containing the values from 1
through 15
, then use the del
statement to perform the following operations consecutively:
Delete a slice containing the first four elements, then show the resulting list.
Starting with the first element, use a slice to delete every other element of the list, then show the resulting list.
Answer:
In [1]: numbers = list(range(1, 16))
In [2]: numbers
Out[2]: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
In [3]: del numbers[0:4]
In [4]: numbers
Out[4]: [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
In [5]: del numbers[::2]
In [6]: numbers
Out[6]: [6, 8, 10, 12, 14]