Home > Articles

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

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
  • + Share This
  • 🔖 Save To Your Account