How to find the index of an item in a List in Python
Learn how the index of an item in Python Lists can be found.
To find the index of an item in Python lists, you can simply use my_list.index()
:
#more
my_list = ["apple", "banana", "cherry"]
my_list.index("banana") # --> 1
my_list.index("cherry") # --> 2
my_list.index("orange") # --> # ValueError: 'orange' is not in list
From the official Python docs:
list.index(x[, start[, end]])
¶
Return zero-based index in the list of the first item whose value is equal to x. Raises a ValueError if there is no such item.
The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument.
In order to deal with possible Exceptions you could wrap the statement in a try-except
block:
try:
idx = my_list.index("orange")
except ValueError:
idx = -1
It only returns the index of the first found item¶
A call to index searches through the list until it finds a match, and stops there.
If you expect to need indices of more matches, you could use a list comprehension or generator expression.
my_list = ["apple", "apple", "cherry"]
my_list.index("apple") # --> 0
idxs = [i for (i, e) in enumerate(my_list) if e == "apple"]
# [0, 1]
enumeration
here. FREE VS Code / PyCharm Extensions I Use
✅ Write cleaner code with Sourcery, instant refactoring suggestions: Link*
Python Problem-Solving Bootcamp
🚀 Solve 42 programming puzzles over the course of 21 days: Link*