__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
- dunder method — A method whose name starts and ends with two underscores, such as __init__ or __len__, which Python calls for you to implement built-in behaviour.
- len() — The built-in function that returns how many items a string, list, tuple, set or dictionary holds.
- string index — The position number of a character in a string or an item in a list, counting from 0 at the left, used in square brackets as s[0].
Taught in
- Dunder Methods, And Making Objects Pythonic — Hands-on Python: Complete Video Course & Book