list.index()
Python · Lists
Theory
.index(value) scans the list from the start and returns the position of the first item equal to value. For sales = [100, 250, 300], sales.index(250) is 1. If the value appears more than once, only the first position is returned. Optional start and stop arguments limit the search to a slice, so sales.index(250, 2) begins searching at index 2 and finds the second 250 in [100, 250, 300, 250].
If the value is not present, index() raises ValueError rather than returning -1 (strings have .find() for that, lists do not). So either check with if value in sales first, or wrap the call in try/except ValueError. The search is linear, O(n), so calling index() repeatedly inside a loop on a big list gets slow. To find every position, use [i for i, v in enumerate(sales) if v == 250], and if you need fast lookups by value, build a dict that maps values to positions.
Why we use it
Sometimes you know a value and need its position: to update the item next to it, to slice from there, or to report where something first appeared. index() gives you that position directly.
When to use it
Use index() for a one-off 'where is it?' when the value surely exists. Use enumerate() with a comprehension to get all positions, in for a yes/no check, and a dict when you look up many values by key.
How it works
- Call sales.index(250)
- Start at index 0 (or the given start)
- Is the item at this index == 250? Yes: Return this index immediately. No: Move to the next index.
- Passed the end (or stop) without a match? Yes: Raise ValueError. No: Keep scanning.
- print shows 1
Syntax
list.index(value)Example
sales = [100, 250, 300]
print(sales.index(250))Key points
- Raises a ValueError if the value isn't present
- Only finds the first match; use enumerate() in a comprehension for all matches
- Optional start/stop arguments limit the search range
- Lists have no find() returning -1; check with in first
- Linear search, O(n): avoid calling it repeatedly on large lists