Implementing __delitem__ in Python
Learn how to implement Python's __delitem__ special method so custom classes support del obj[key], handle missing keys, and stay consistent with __getitem__ and __setitem__.

Python's __delitem__ method is what makes del obj[key] work on custom objects. When you implement this special method, your class gains the ability to delete items using the familiar subscript syntax, just like a list or dictionary. This is part of the Python data model that lets user-defined classes participate in language features that otherwise only work for built-in types.
The Role of __delitem__ in Python's Data Model
__delitem__ is one of the three core methods that define the mutable mapping protocol, alongside __getitem__ and __setitem__. While __getitem__ reads a value and __setitem__ writes a value, __delitem__ removes an item. The interpreter invokes it whenever you use the del statement with a subscript, such as del obj[key]. The default mixin methods inherited from collections.abc.MutableMapping, such as pop(), also call this method when they remove an item.
For a class to be considered a mutable container, it typically needs all three methods. Without __delitem__, the del statement will raise a TypeError indicating that the object doesn't support item deletion. Implementing it correctly gives your class the same deletion semantics as built-in dictionaries and lists.
Implementing __delitem__ in a Custom Class
The basic implementation is straightforward. You define a method named __delitem__ that takes a key argument and removes the corresponding item from your internal storage. Here is a minimal example of a class that wraps a dictionary:
class SimpleDict:
def __init__(self):
self._data = {}
def __getitem__(self, key):
return self._data[key]
def __setitem__(self, key, value):
self._data[key] = value
def __delitem__(self, key):
del self._data[key]With this class, you can now write:
obj = SimpleDict()
obj["name"] = "Alice"
print(obj["name"]) # Alice
del obj["name"]
# Accessing obj["name"] now raises KeyErrorThe __delitem__ method simply delegates to the underlying dictionary's del operation. This pattern works well when you are wrapping an existing container and want to add behavior like logging or validation before deletion.
How del Interacts with __delitem__
When you write del obj[key], Python calls type(obj).__delitem__(obj, key). The method receives the object and the key. It must perform the deletion and return None. The interpreter does not check whether the key exists before calling the method; that responsibility lies entirely with your implementation. If the key is not present, you should raise an appropriate exception, typically KeyError for mapping-like objects or IndexError for sequence-like objects.
This design gives you full control over the deletion behavior. For example, you might decide that deleting a missing key should be a no-op instead of an error, though that deviates from the standard container behavior and can surprise users.
Error Handling: Raising KeyError and IndexError
To match the behavior of built-in containers, your __delitem__ should raise KeyError when the key is not found. Here is an improved version of the previous example that checks for existence:
class SafeDict:
def __init__(self):
self._data = {}
def __getitem__(self, key):
return self._data[key]
def __setitem__(self, key, value):
self._data[key] = value
def __delitem__(self, key):
if key not in self._data:
raise KeyError(key)
del self._data[key]For sequence-like classes, you should raise IndexError for an invalid index. The exact exception depends on the semantics of your container. If you are building a custom list, follow the list behavior: deleting an index outside the range raises IndexError. If you are building a mapping, use KeyError. Choosing the correct exception is important because callers often catch these specific exceptions to handle missing items.
Consistency with __getitem__ and __setitem__
A well-designed container maintains consistency across its read, write, and delete operations. If __getitem__ raises KeyError for a key, then __delitem__ should also raise KeyError for that same key. After a successful deletion, subsequent calls to __getitem__ with that key should raise KeyError. Similarly, __setitem__ should allow re-inserting a deleted key. This consistency ensures that your object behaves predictably and can be used as a drop-in replacement for built-in mappings.
When you implement the element-access methods, you can also inherit from collections.abc.MutableMapping to get mixin methods like pop(), clear(), setdefault(), and update(). The ABC requires __getitem__, __setitem__, __delitem__, __iter__, and __len__; the mixin methods use your implementations for element access. For example, the default pop() implementation calls __getitem__ to fetch the value and then __delitem__ to remove it. This reduces boilerplate and ensures your class follows the expected protocol.
Performance and Memory Considerations
Every del obj[key] call goes through a Python method dispatch, which is slower than the direct C-level operation on built-in types. For most applications, this overhead is negligible, but it matters in tight loops that perform many deletions. If performance is critical, consider whether a custom container is necessary or whether you can use a built-in type with a thin wrapper.
Memory behavior depends on how you store the data. If you are using a dictionary internally, deletion frees the reference to the value, allowing the garbage collector to reclaim it if no other references exist. If you are implementing a custom data structure, ensure that __delitem__ actually releases the reference and does not leave stale entries in an internal list or array. For example, deleting from an internal list by index should remove the element, either with pop(index) or del self._data[index], rather than just setting the slot to None.
Another consideration is that __delitem__ can be called with a slice object for sequence types. For instance, del my_list[1:3] invokes __delitem__ with a slice. If you are implementing a sequence, you must handle slice arguments, either by supporting them directly or by raising TypeError if your container does not support slice deletion. The built-in list supports slices, and any custom sequence that aims for compatibility should too.
Common Pitfalls and Edge Cases
One frequent mistake is forgetting to raise KeyError when the key is missing. If your method silently does nothing, the del statement appears to succeed, but the item remains. This can lead to subtle bugs where later code still sees the item. Always match the exception behavior of built-in containers.
Another pitfall is mutating the container while iterating over it. If you delete items from a dictionary or list during a for loop, you may get a RuntimeError or skip elements. This is not specific to __delitem__, but it is a common issue when you implement a custom container that is used in iteration. To avoid it, collect the keys or indices to delete first, then perform the deletions after the loop.
When implementing __delitem__ for a sequence, be careful about the distinction between deleting by index and deleting by value. The del statement always uses the key or index provided in the subscript. If you want to delete by value, you need a separate method like remove(). Do not try to overload __delitem__ to guess whether the argument is a value or an index; that leads to ambiguous behavior.
Finally, consider what happens when a container is mutated while code is iterating over it. Python's built-in dict raises RuntimeError if its size changes during iteration. A custom container should either provide similar protection or clearly document that deleting entries during iteration is not supported.
By understanding these details, you can implement an __delitem__ method that feels native to Python users and works reliably in real-world code. The method is small but central to creating custom containers that integrate seamlessly with the language's syntax and protocols.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.