liveBook · Manning

Del statement

As explained in The Quick Python Book, Fourth Edition

A del statement is Python syntax for deleting names, items, or slices from objects that support deletion.

Use `del` to remove a list item or slice, a dictionary entry, or a variable name. What disappears depends on the target: deleting a name does not necessarily delete the object it referred to. section 5.3 section 7.2 section 4.3

Delete by list position

Start with `x = ['a', 2, 'c', 7, 9, 11]`. After `del x[1]`, `x` is `['a', 'c', 7, 9, 11]`. Then `del x[:2]` leaves `[7, 9, 11]`. For lists, `del x[n]` has the effect of `x[n:n+1] = []`, and `del x[m:n]` has the effect of `x[m:n] = []`. `del` is usually easier to read. section 5.3

To remove a dictionary key-value pair, use its key: `del english_to_french['green']` removes the `'green'` entry. This differs from list deletion by position; `list.remove(value)` instead searches for the first matching list value. section 7.2 section 5.3

To delete a variable name, write `del x`. If `x = 5` beforehand, a subsequent `print(x)` raises `NameError` because `x` is no longer defined. Deleting the name does not necessarily destroy its former object. section 4.3

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains list deletion through equivalent slice assignments and shows dictionary and variable deletion; stops short of object-lifetime internals.
Examples
Shows successive item and slice deletions, removal of a dictionary entry, and a NameError after deleting a variable.
What it assumes
Assumes familiarity with lists, indices, dictionary keys, and assignment; illustrates deletion with small examples.
What you can do after
Apply it via Python syntax to remove selected list contents, dictionary entries, or names, while distinguishing name deletion from object deletion.
How it connects
Connects deletion to list indexing, slice assignment, dictionary keys, variable references, and NameError.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.