list · Python
x in items / index
Searches from the front with ==.
x in items; list.index(x[, start[, end]])
Complexity
| Best case | O(1) |
|---|---|
| Average | O(n) |
| Worst case | O(n) |
| Extra space | O(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
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.