How to find the index of an item in a List in Python

To find the index of an item in Python lists, you can simply use my_list.index():

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-exceptblock:

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]

You can learn more about list comprehension here, and more about enumeration here.

FREE VS Code / PyCharm Extensions I Use

🪁 Code faster with Kite, AI-powered autocomplete: Link *

✅ Write cleaner code with Sourcery, instant refactoring suggestions: Link *

* These are affiliate links. By clicking on it you will not have any additional costs, instead you will support me and my project. Thank you! 🙏

Check out my Courses