__len__ and __getitem__

The pair of dunder methods that make your objects work with len(), indexing obj[i] and, as a result, for loops.

In more detail

__len__ returns the item count and __getitem__(i) returns the item at position i, raising IndexError past the end. With both defined, an object behaves like a read-only sequence.

Related terms

Taught in

References