Python Reference ยท Statements and Keywords
The del statement
Reference for the Python del statement: remove variables, list items, slices, dictionary keys and attributes, plus how it differs from pop() and remove().
The del statement removes things: a variable name, an item from a list or dictionary, a slice of a list, or an attribute from an object. It works on the target itself, not on a value, so del x removes the name x, and del items[0] removes position 0 from the list items.
del never deletes objects directly. It only removes a reference; the object is freed later, once nothing else refers to it.
del scores["ada"]
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
del name del name1, name2 del sequence[index] del sequence[start:stop:step] del mapping[key] del obj.attribute
| Target | Effect |
|---|---|
del name |
Unbinds the variable from the current scope. Later use raises NameError (or UnboundLocalError). |
del seq[i] |
Removes one item from a mutable sequence; later items shift down. |
del seq[a:b:c] |
Removes the whole slice. Extended slices (with a step) must match exactly the selected items. |
del d[key] |
Removes the key and its value from a dictionary. |
del obj.attr |
Removes an instance attribute (calls __delattr__()). |
Raises: NameError for an unbound name, IndexError for an index out of range, KeyError for a missing key, AttributeError for a missing attribute, TypeError for objects that do not support item deletion (strings, tuples).
Usage notes
- Removes a reference, not an object. After
b = a; del a, the list is still alive throughb. - Shifts indexes. Deleting from a list while iterating forward skips items. Iterate backwards, build a new list, or use a comprehension.
delvspop().list.pop(i)removes and returns the item;delremoves without returning anything.list.remove(v)deletes by value.del lst[:]clears a list in place, likelst.clear().lst = []instead rebinds the name and leaves other references untouched.- Cost. Deleting near the front of a long list is O(n); use
collections.dequefor frequent removals at both ends. - Not for immutables. Strings and tuples do not support item deletion; build a new one with slicing.
- Rarely needed for names. Variables vanish when a function returns. Use
delfor large temporary objects in long-lived scopes or to hide helper names in a module. - Tuples of targets are allowed:
del a, b[0], c.x.
Related
list.pop(),list.remove(),dict.pop(),delattr()- Slicing,
KeyError - Lessons: Lists, Dictionaries