How to get the index of an item in a Python list

Published on Aug. 22, 2023, 12:15 p.m.

To get the index of an item in a Python list, you can use the index() method of the list object. Here’s an example:

my_list = ["apple", "banana", "cherry", "apple", "cherry"]
index = my_list.index("banana")
print("Index of 'banana':", index)

In this example, we have a list of fruits called my_list. We use the index() method to find the index of “banana” in the list and store it in the index variable. We then print the index.

Note that if the desired item is not in the list, index() will raise a ValueError. To avoid this, you can either check if the item is in the list using the in operator or use a try-except block to catch the error.

Tags:

related content