list · Python

x in items / index

Searches from the front with ==.

x in items; list.index(x[, start[, end]])

Complexity

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

A linear scan. Use a set for repeated membership tests, or bisect on a sorted list.

Tested example

colors = ["red", "green", "blue"]
assert "green" in colors  # linear scan comparing with ==
assert colors.index("blue") == 2
try:
    colors.index("purple")
    raise AssertionError("expected ValueError")
except ValueError:
    pass
Runs in the test suite on CPython 3.14.0 · examples/python/tests/test_collections_list.py

Parameters

x
The value to find.

Behaviour

Returns
`in`: a bool. index: the first position.
Errors and preconditions
index raises ValueError if x is absent.
Changes
Nothing.
Memory and invalidation
No allocation.

See it step by step: the Binary search: halving a sorted range lesson has an interactive 3D visualizer of the same mechanism.