- 5.1 Introduction
- 5.2 Lists
- 5.3 Tuples
- 5.4 Unpacking Sequences
- 5.5 Sequence Slicing
- 5.6 del Statement
- 5.7 Passing Lists to Functions
- 5.8 Sorting Lists
- 5.9 Searching Sequences
- 5.10 Other List Methods
- 5.11 Simulating Stacks with Lists
- 5.12 List Comprehensions
- 5.13 Generator Expressions
- 5.14 Filter, Map and Reduce
- 5.15 Other Sequence Processing Functions
- 5.16 Two-Dimensional Lists
- 5.17 Intro to Data Science: Simulation and Static Visualizations
- 5.18 Wrap-Up
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