access
list.index
Returns the zero-based index of the first item equal to x within the optional [start, end) range. Raises ValueError if no match is found.
list.index(x[, start[, end]]) Parameters
| Parameter | Purpose |
|---|---|
| x | Value to find; compared with ==. |
| start (optional) | Index at which to begin the search. |
| end (optional) | Index at which to stop (exclusive); like a slice, out-of-range is clamped. |
Examples
>>> lst = ['a', 'b', 'c', 'b']
>>> lst.index('b')
1 Returns the first match's index.
>>> lst = ['a', 'b', 'c', 'b']
>>> lst.index('b', 2)
3 Search from index 2 onward.
>>> [1, 2, 3].index(9)
ValueError: 9 is not in list Missing value raises ValueError — check with `in` first or use try/except.
>>> lst = [1, 2, 3, 4]
>>> lst.index(3, 0, 2)
ValueError: 3 is not in list The end argument is exclusive; 3 is at index 2, outside [0, 2).
Gotcha
Raises ValueError when x is absent — always guard. The end argument is EXCLUSIVE, matching slice semantics.
Related methods
list.count
Returns the number of times x appears in the list. Comparison uses equality; returns 0 if x is not present (never raises).
x in list
Membership test operator that returns True if any element equals x, else False. Runs in O(n) — for repeated lookups, convert to a set (O(1) per test).
list[i] / list[i:j:k]
Subscript syntax to read a single element (by index) or a new list (by slice). Slicing always returns a new shallow copy; out-of-range slice bounds are silently clamped while single-index access raises IndexError.
← All Python list methods · Dict methods · list vs tuple vs set