proomt

Search

Search posts, papers, and topics

All posts

Lerner Consulting BlogReuven Lerner1 min readintermediate

Python in operator: How __contains__ speeds up membership tests

Summary

The post explains that Python’s `in` operator first looks for a `__contains__` method on the object and uses its boolean result; if absent it falls back to iterating via `__iter__`. Implementing `__contains__` can make membership checks faster, especially for large collections, by avoiding full iteration.

  • `in` → `obj.__contains__(item)` if defined, else `for x in obj: if x == item`.
  • Custom containers can gain O(1)‑ish membership checks by providing an efficient `__contains__` (e.g., a hash‑based lookup).
  • Built‑in containers like `set` and `dict` already implement fast `__contains__` and are preferred when frequent membership tests are needed.
  • If you only need iteration, you can skip `__contains__`; but adding it is cheap and improves performance for callers that use `in`.

Membership tests are common in Python code; using a container with an efficient `__contains__` can cut runtime dramatically for large data sets, and the behavior is part of the language contract that developers should be aware of when designing custom collections.

4/10

Related reading

  1. Quiz: Thinking Recursively in Python

    This is an interactive quiz from Real Python designed to test understanding of recursive thinking in Python. It covers identifying recursive structures, writing base and recursive cases, managing state, and using caching to avoid recomputation.

    Real Pythonrealpython.com1 min