Python Glossary Русский

all Python 3Sets (set)term

in / not in for sets — O(1)

search

A membership test on a set takes O(1) (a hash table), unlike O(n) for lists.

Syntax

item in s  |  item not in s

The O(1) is an average over the hash table rather than a guarantee, and it requires the value to be hashable — looking up a list raises TypeError. Converting a list to a set for one membership test gains nothing, because building the set is O(n); it only pays off when you test many times.

Examples

s = {1, 2, 3, 4, 5}
print(3 in s)
# → True
print(6 in s)
# → False
print(6 not in s)
# → True
big = set(range(10**6))
print(999999 in big)
# → True (мгновенно, O(1))
banned = {'spam', 'ads', 'junk'}
msg = 'spam email'
print(any(w in banned for w in msg.split()))
# → True

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy