The __getitem__ method is the special (dunder) method Python calls when you use square brackets on an object. obj[key] runs type(obj).__getitem__(obj, key). Implement it to make your own classes behave like sequences or mappings, with support for integer indexes, string keys, tuples and slices.
Because Python looks the method up on the class, defining __getitem__ also makes an object iterable through the old sequence protocol and enables the in operator, even if you never write __iter__ or __contains__.
The type of key depends on how the caller writes the expression:
| Expression | Value of key |
|---|---|
obj[2] | the integer 2 |
obj["name"] | the string "name" |
obj[1, 2] | the tuple (1, 2) |
obj[1:4] | slice(1, 4, None) |
obj[::2] | slice(None, None, 2) |
obj[1:3, 0] | the tuple (slice(1, 3, None), 0) |
You decide what each form means. The convention is to raise IndexError for an invalid sequence index, KeyError for a missing mapping key, and TypeError for a key of the wrong type.
The simplest implementation delegates to a built-in list. Indexing, negative indexes and slicing then work for free:
The for loop works because Python falls back to calling __getitem__ with 0, 1, 2 and so on until it receives an IndexError. Delegating to the list produces that error at the right moment.
When you do not delegate to a built-in, check for slice and use slice.indices() to turn it into valid start, stop and step values:
Using key.indices(len(self)) handles negative values, open ends and out-of-range slice bounds the same way built-in lists do. For integer-like keys such as NumPy integers, call operator.index(key) instead of isinstance(key, int).
A class can also act as a dictionary. For missing keys, raise KeyError so that in checks, dict.get-style wrappers and error messages work as callers expect:
Returning a placeholder such as "Key not found" for missing keys hides bugs, because callers cannot tell a real value from an error. Raise an exception, or add a separate get(key, default) method.
Comma-separated indexes arrive as a tuple, which is how matrices and grids are usually modelled:
For real numerical work, use NumPy arrays, which already support rich indexing.
__getitem__ only reads. Pair it with the other container methods as needed:
__setitem__(self, key, value) for obj[key] = value.__delitem__(self, key) for del obj[key].__len__ for len(obj).__iter__ and __contains__ for faster, explicit iteration and in checks.__class_getitem__ for generic type syntax such as MyClass[int]. This is a different hook that runs on the class, not on instances.If you inherit from collections.abc.Sequence or Mapping and implement __getitem__ and __len__, you get __iter__, __contains__, index(), count() and more as mixin methods.
__getitem__ and __getattr__?__getitem__ handles obj[key] with square brackets. __getattr__ handles missing attributes written as obj.name.
__getitem__ make an object iterable?Yes, through the legacy sequence protocol: Python calls it with 0, 1, 2 and so on until IndexError. Prefer defining __iter__ for clarity and speed.
Delegate to a built-in sequence, or add len(self) to negative integers yourself. slice.indices() handles negative slice bounds.
__getitem__ raise?Raise IndexError for sequences and KeyError for mappings. Raise TypeError for unsupported key types.
__getitem__ defines how square-bracket access works on your class. Handle integers, slices and tuples as needed, raise IndexError or KeyError for bad keys, and combine it with __len__ or the collections.abc base classes to build complete, well-behaved containers.