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

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

To find the index of an element in a list in Python, you can use the index() method. The index() method returns the index position of the first occurrence of the specified element in the list. If the element is not present in the list, a ValueError exception is raised.

Here’s an example:

my_list = ['apple', 'banana', 'orange']
index = my_list.index('banana')
print(f"The index of 'banana' is {index}")

Output:

The index of 'banana' is 1

In this example, we define a list of fruits and then use the index() method to find the index position of the element ‘banana’. Since ‘banana’ is present in the list at index 1, the program prints “The index of ‘banana’ is 1”.

If the element is not present in the list, the index() method will raise a ValueError exception:

my_list = ['apple', 'banana', 'orange']
try:
    index = my_list.index('pear')
    print(f"The index of 'pear' is {index}")
except ValueError:
    print("The element 'pear' is not present in the list")

Output:

The element 'pear' is not present in the list

In this example, we try to find the index position of the element ‘pear’, which is not present in the list. Since the index() method raises a ValueError exception in this case, the try block catches the exception and the program prints “The element ‘pear’ is not present in the list”.

Tags: