__delitem__ — Easy Examples
Enables item deletion with del obj[key]
Implementing __delitem__
Basic implementation of __delitem__ in a class.
python
class TrackedDict: def __init__(self): self._data = {"a": 1, "b": 2, "c": 3} def __delitem__(self, key): print(f"Deleting key: {key}") del self._data[key] d = TrackedDict() del d["b"] print(d._data)
__delitem__ enables item deletion with del obj[key]. Implementing it lets you customize how Python interacts with your objects.
__delitem__ in action
Seeing __delitem__ called by Python's built-in operations.
python
# How Python calls __delitem__ automatically class Demo: def __init__(self, value): self.value = value def __delitem__(self, other): print(f"__delitem__ was called!") return self d = Demo(42) # This triggers __delitem__: print(d)
Python automatically calls __delitem__ when you use the corresponding operator or function on your object.
Want to try these examples interactively?
Open Easy Playground