How to find the index of an item in a list with Python?

Estimated read time 2 min read

To find the index of an item in a list in Python, you can use the index() method. The index() method returns the first index at which a specified item is found in the list. Here’s an example:

my_list = ['apple', 'banana', 'cherry', 'banana', 'orange']

# Find the index of 'banana'
index = my_list.index('banana')
print(index)

In this example, the index() method is called on the my_list list with the argument 'banana'. The method searches for the first occurrence of 'banana' in the list and returns its index. The index is then printed to the console.

After executing the code, the index of the first occurrence of 'banana' in the list will be printed. In this case, the index will be 1 since 'banana' is found at index 1 in the list.

If the item is not found in the list, a ValueError will be raised. To handle this, you can enclose the index() method call in a try-except block to catch the exception:

try:
    index = my_list.index('banana')
    print(index)
except ValueError:
    print("Item not found in the list")

This way, if the item is not found, the error will be caught and the “Item not found in the list” message will be printed instead of raising an exception.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply