set · Python

elem in s

Tests membership.

elem in s

Complexity

AverageO(1)
Worst caseO(n)
Extra spaceO(1)

One hash and a short probe, instead of the O(n) scan `in` does on a list.

Tested example

words = {"apple", "pear"}
assert "apple" in words  # hash, then ==
assert "Apple" not in words  # no custom comparer: normalise the keys yourself
Runs in the test suite on CPython 3.14.0 · examples/python/tests/test_collections_set.py

Parameters

elem
The element.

Behaviour

Returns
A bool.
Errors and preconditions
TypeError for an unhashable element (sets of sets need frozenset).
Changes
Nothing.
Memory and invalidation
No allocation.