Find the index of an item in a Python list
Find the first or every matching list index, handle missing values, and search by a condition with enumerate and next.
Use items.index(value) to get the zero-based index of the first equal item. If no item matches, it raises ValueError.
fruits = ['apple', 'banana', 'cherry', 'banana']
assert fruits.index('banana') == 1
assert fruits.index('banana', 2) == 3 # Search from index 2
An optional end argument limits the search to a slice-like interval; the returned index still refers to the original list.
Find every match or search by a condition
matches = [i for i, fruit in enumerate(fruits) if fruit == 'banana']
assert matches == [1, 3]
numbers = [3, 8, 15, 7]
first = next((i for i, number in enumerate(numbers) if number > 10), None)
assert first == 2
The default None distinguishes “not found” from a valid index. Without a default, next() raises StopIteration when there is no match.
Handle a missing value
try:
index = fruits.index('mango')
except ValueError:
index = None
You can check 'mango' in fruits first, but a successful search then scans for the item twice. Avoid accidentally using -1 as a missing-value sentinel to index the list: in Python, it selects the last element.
FAQ
How expensive is index()?
It performs a linear search, taking O(n) comparisons in the worst case. For repeated lookups, a dictionary can map values to positions if you define how duplicates should be handled. A set answers membership, not position. Binary search requires sorted data and an equality check at the candidate position.
What about NumPy arrays?
For a one-dimensional array, np.where(array == value)[0] returns matching indices. With a multidimensional array, np.where returns one index array per dimension; taking only [0] is not a complete coordinate list.
Contact us
Join the community
to join the community
Try Guance
Start online and pay only for what you use.
Get startedChoose a Guance plan