Python __delitem__ Method
Last modified November 17, 2026 Python 3.15
The del statement removes an item with del obj[key],
and the class method that implements it is __delitem__. It is the
counterpart of __getitem__ and __setitem__, completing
the mutable container protocol. This article shows the dispatch, how slices are
passed, how to extend a built-in dictionary, and how to reject deletions that
would break a container's invariants.
How del removes an item
del obj[key] is evaluated as
type(obj).__delitem__(obj, key). The method's return value is
ignored, because del is a statement rather than an expression. A
class without the hook is not a mutable mapping and raises
TypeError when item deletion is attempted.
class Inventory:
def __init__(self, **items):
self.items = dict(items)
def __getitem__(self, key):
return self.items[key]
def __delitem__(self, key):
print(f"removing {key}")
del self.items[key]
def __len__(self):
return len(self.items)
inv = Inventory(apples=10, pears=5)
del inv["apples"]
print(inv.items)
print(len(inv))
try:
del inv["plums"]
except KeyError as e:
print(type(e).__name__, e)
class Plain:
pass
try:
del Plain()["key"]
except TypeError as e:
print(type(e).__name__, e)
The hook delegates to the inner dictionary, so a missing key produces the usual
KeyError with the key as its argument. The plain class has no
__delitem__, and the interpreter reports that its instances do not
support item deletion. Adding __len__ and __getitem__
without __delitem__ still leaves the object read-only.
$ python basic_delitem.py
removing apples
{'pears': 5}
1
removing plums
KeyError 'plums'
TypeError 'Plain' object does not support item deletion
Slices arrive as slice objects
del obj[start:stop:step] calls __delitem__ once, with a
slice object instead of an integer or a string. The hook must detect
that type and handle it, usually by forwarding the slice to an underlying list
or by computing the affected indices itself.
class Numbers:
def __init__(self, values):
self.values = list(values)
def __delitem__(self, key):
print("key:", key)
del self.values[key]
def __repr__(self):
return f"Numbers({self.values})"
n = Numbers(range(10))
print(n)
del n[2:5]
print(n)
del n[::3]
print(n)
The first deletion removes indices 2, 3, and 4, leaving seven values. The
extended slice then removes every third remaining element, starting with the
first. Printing the key shows that Python passes slice(2, 5, None)
and slice(None, None, 3), not a list of indices, so the hook never
sees the individual positions.
$ python slices.py Numbers([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) key: slice(2, 5, None) Numbers([0, 1, 5, 6, 7, 8, 9]) key: slice(None, None, 3) Numbers([1, 5, 7, 8])
Extending a built-in mapping
Subclassing dict is a compact way to add behaviour to a mapping.
The override calls super().__delitem__() so the actual removal and
the error handling stay with the built-in type, while the subclass adds logging
or bookkeeping around it.
class LoggedDict(dict):
def __delitem__(self, key):
print(f"deleting {key!r}")
super().__delitem__(key)
d = LoggedDict(host="localhost", port=5432)
del d["port"]
print(d)
try:
del d["user"]
except KeyError as e:
print(type(e).__name__, e)
The successful removal is logged and then performed by dict. The
missing key also reaches the override, prints its message, and then fails inside
super(). If the log should record only successful deletions, move
the print after the super() call.
$ python logged_dict.py
deleting 'port'
{'host': 'localhost'}
deleting 'user'
KeyError 'user'
Enforcing deletion rules
A container can protect entries that are required for its own consistency. The
check runs before the underlying dictionary is touched, and raising
KeyError is appropriate because the caller is using the mapping
interface. The message can explain the rule instead of just naming the key.
class Config:
required = {"host", "port"}
def __init__(self, **values):
self.values = dict(values)
def __delitem__(self, key):
if key in self.required:
raise KeyError(f"{key} is required")
del self.values[key]
def __repr__(self):
return f"Config({self.values})"
config = Config(host="localhost", port=5432, debug=True)
print(config)
del config["debug"]
print(config)
try:
del config["host"]
except KeyError as e:
print(type(e).__name__, e)
print(config)
The optional flag is removed, while the host raises a custom error and stays in place. Note that the check runs for every key, so a required key that is somehow missing would still raise the "required" message rather than the usual missing key error. That is acceptable when the invariant guarantees presence, but the order of checks should be deliberate.
$ python constraints.py
Config({'host': 'localhost', 'port': 5432, 'debug': True})
Config({'host': 'localhost', 'port': 5432})
KeyError 'host is required'
Config({'host': 'localhost', 'port': 5432})
Deleting a column from a table
The key does not have to be a position. A table can use column names as keys, so
del table["age"] removes the header and the corresponding cell from
every row. This is a realistic example of a container whose unit of deletion
spans several internal lists.
class Table:
def __init__(self, headers, rows):
self.headers = list(headers)
self.rows = [list(row) for row in rows]
def __delitem__(self, header):
index = self.headers.index(header)
del self.headers[index]
for row in self.rows:
del row[index]
def __repr__(self):
lines = [", ".join(self.headers)]
lines += [", ".join(map(str, row)) for row in self.rows]
return "\n".join(lines)
table = Table(["name", "age", "city"], [
["Alice", 30, "Bratislava"],
["Bob", 25, "Kosice"],
])
print(table)
del table["age"]
print(table)
try:
del table["salary"]
except ValueError as e:
print(type(e).__name__, e)
The column index is found once and then reused for the header and every row, so
the table stays rectangular. An unknown header fails inside
list.index() with ValueError. A mapping-like container
would normally translate that into KeyError; the choice depends on
whether the object presents itself as a sequence or as a dictionary.
$ python table.py name, age, city Alice, 30, Bratislava Bob, 25, Kosice name, city Alice, Bratislava Bob, Kosice ValueError list.index(x): x not in list
Best practices
Item deletion changes the shape of a container, so keep the protocol complete and the failure modes clear:
- Implement
__getitem__,__setitem__, and__delitem__together for a mutable container; a missing hook makes the object partially usable. - Handle
sliceexplicitly when the container supports sequence syntax, and decide whether extended slices are allowed. - Raise
KeyErrorfor a missing mapping key andIndexErrorfor an out-of-range sequence index. - Delegate to
super().__delitem__()in built-in subclasses, and place logging before or after the call according to what should be recorded. - Validate invariants before mutating, so a failed deletion leaves the container unchanged.
- Do not return a value; the result of
delis discarded.
Source
object.__delitem__ - Python documentation
Emulating container types - Python documentation
Mapping types - Python documentation
In this article we have implemented the __delitem__ method. We have
covered the del dispatch, slice keys, dictionary subclassing,
protected entries, and column deletion in a table. For related topics, see
Python __getitem__ method,
Python __setitem__ method,
Python __del__ method, and
Python __contains__ method.
Author
List all Python tutorials.