5.6 del Statement

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

Deleting the Element at a Specific List Index

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]

Deleting a Slice from a List

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]

Deleting a Slice Representing the Entire List

The following code deletes all of the list’s elements:


In [9]: del numbers[:]

In [10]: numbers
Out[10]: []

Deleting a Variable from the Current Session

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

tick mark Self Check

  1. (Fill-In) Given a list numbers containing 1 through 10, del numbers[-2] removes the value _____ from the list.
    Answer: 9.

  2. (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:

    1. Delete a slice containing the first four elements, then show the resulting list.

    2. 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]