all Python 3Lists (list)term
in / not in for lists
search
Checks whether an item is present in the list, in O(n). Returns a bool.
Syntax
item in lst | item not in lst
The scan is linear, so repeating it inside a loop quietly turns into O(n squared) — if you probe the same collection often, put it in a set, where the test is near-instant (at the price of hashable elements and lost order). Membership compares with ==, not by type, so True and 1 count as the same element. And unlike strings, where in means substring, a list checks for one whole element, never a sub-sequence.
Examples
lst = [1, 2, 3, 4, 5]
print(3 in lst)
# → True
print(6 in lst)
# → False
print(6 not in lst)
# → True
print([1, 2] in [[1, 2], [3, 4]])
# → True (сравнение подсписков)
print(None in [1, None, 3])
# → True
See also
Open in the full glossarydocs.python.orgReport an inaccuracy