__delitem__

def __delitem__(self, key)
Returns: None · Updated March 18, 2026 · Dunder Methods
python dunder-methods container-types

__delitem__ is called to implement deletion of items using the del statement. When you write del obj[key], Python calls obj.__delitem__(key).

Basic Usage

Define __delitem__ in your class to handle deletion of items by key or index:

class MyContainer:
    def __init__(self):
        self.data = {'a': 1, 'b': 2, 'c': 3}

    def __delitem__(self, key):
        del self.data[key]

container = MyContainer()
del container['b']  # Calls __delitem__
print(container.data)  # {'a': 1, 'c': 3}

The method receives the key used in the deletion and performs the actual removal. It must return None.

Common Use Cases

Dictionary-like Classes

Create custom dictionaries with logging, validation, or constrained deletion:

class LoggingDict(dict):
    def __delitem__(self, key):
        print(f"Deleting key: {key}")
        super().__delitem__(key)

d = LoggingDict({'red': '#FF0000', 'green': '#00FF00'})
del d['green']  # Prints: Deleting key: green

Protected Keys

Prevent deletion of certain keys:

class ProtectedContainer:
    def __init__(self):
        self._data = {'config': {}, 'cache': {}}
        self._protected = {'config'}

    def __delitem__(self, key):
        if key in self._protected:
            raise KeyError(f"Cannot delete protected key: {key}")
        del self._data[key]

pc = ProtectedContainer()
del pc['config']  # Raises KeyError
del pc['cache']   # Works

List-like Classes with Slicing

Support both single index and slice deletion:

class MyList:
    def __init__(self, items):
        self.items = list(items)

    def __delitem__(self, index):
        del self.items[index]

lst = MyList([10, 20, 30, 40, 50])
del lst[1]        # Delete single item
del lst[0:2]      # Delete slice

Key Points

  • Signature: def __delitem__(self, key) — takes the key/index to delete
  • Return value: Must return None
  • Raises: KeyError for missing keys (like dict), IndexError for out-of-bounds integer indices
  • Slice support: Slice objects work automatically if your internal storage supports them

Error Handling

Handle missing keys gracefully:

class SafeDict(dict):
    def __delitem__(self, key):
        if key in self:
            super().__delitem__(key)
        else:
            print(f"Key '{key}' not found, nothing to delete")

d = SafeDict({'a': 1, 'b': 2})
del d['a']    # Removes 'a'
del d['z']    # Prints message, no error
  • __getitem__ — enables obj[key] access
  • __setitem__ — enables obj[key] = value
  • __iter__ — enables iteration over container

See Also