Python › Magic Methods & Operator Overloading

How do __len__, __getitem__, and __setitem__ let a custom class act like a sequence or mapping?

Intermediate

Answer

__len__ enables len(obj); __getitem__ enables obj[key] (and, historically, iteration and 'in' checks via integer index fallback); __setitem__ enables obj[key] = value. Implementing these lets custom container classes integrate naturally with built-in syntax, slicing, and functions expecting sequence-like or mapping-like behavior.
class Deck:
    def __init__(self):
        self._cards = list(range(52))
    def __len__(self):
        return len(self._cards)
    def __getitem__(self, i):
        return self._cards[i]

d = Deck()
print(len(d), d[0], d[-1])
Real-world example A custom Matrix class implements __getitem__ and __setitem__ to support matrix[row, col] indexing via tuple keys, mimicking NumPy-style access.

Common follow-ups: How does __getitem__ enable iteration without __iter__?;What does __contains__ do differently from relying on __getitem__?