Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Classes and Special Methods

__len__() and __getitem__()

Reference for Python __len__, __getitem__, __setitem__, __delitem__ and __contains__: building sequence and mapping classes, slices and the old iteration fallback.

A few special methods let your own classes behave like lists and dictionaries. __len__() powers len(obj), __getitem__() powers obj[key], __setitem__() powers obj[key] = value, __delitem__() powers del obj[key] and __contains__() powers x in obj.

Define these and your objects work with indexing, slicing, for loops, reversed(), in and many built-ins, without inheriting from list.

Python
class Deck:
    def __init__(self, cards):
        self._cards = list(cards)
    def __len__(self):
        return len(self._cards)
    def __getitem__(self, index):
        return self._cards[index]

Try it

Python A sequence class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python A mapping class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
class C:
    def __len__(self) -> int: ...
    def __getitem__(self, key): ...
    def __setitem__(self, key, value): ...
    def __delitem__(self, key): ...
    def __contains__(self, item) -> bool: ...
Method Used by
__len__() len(obj). Also decides truthiness when __bool__() is missing: length 0 is false.
__getitem__(key) obj[key], including slices (key is a slice object) and tuples (obj[1, 2]).
__setitem__(key, value) obj[key] = value.
__delitem__(key) del obj[key].
__contains__(item) item in obj.

Return value: __len__() must return an integer greater than or equal to 0. The others return whatever suits the class.

Raises: by convention IndexError for a bad sequence index and KeyError for a missing mapping key. len() raises TypeError if __len__() returns a non-integer and ValueError if it is negative.

Usage notes

  • Sequences vs mappings. Sequences accept integers (including negative ones) and slices and raise IndexError; mappings accept any hashable key and raise KeyError.
  • Slices arrive as slice objects. Handle them with isinstance(index, slice) or by forwarding the key to an underlying list, which accepts slices itself.
  • Iteration fallback. If a class has no __iter__() but has __getitem__(), for tries 0, 1, 2, ... until IndexError. This is why Squares() is iterable. Prefer a real __iter__() in new code.
  • in fallback. Without __contains__() Python uses __iter__(), then the __getitem__() fallback, which can be slow.
  • Reverse order. reversed(obj) needs __len__() and __getitem__() (or __reversed__()).
  • Truthiness. An empty container is false, because __len__() returns 0 (the bool(Playlist()) line).
  • Inherit instead from collections.abc.Sequence or MutableMapping to get many methods (index, count, get, items, ...) once you define the basic ones.
  • Missing keys on dict subclasses. dict subclasses can define __missing__(); defaultdict uses it.