Python in operator: How __contains__ speeds up membership tests

Python in operator: How __contains__ speeds up membership tests

How does the “in” operator work in Python?

– If an object defines __contains__, then its (boolean) result is returned (coerced to bool).
– If not, then Python iterates over it with __iter__

Can you find and return a result faster than __iter__? Then define __contains__.