How to get the index of an element in Python List

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

To get the index of an element in a Python list, you can use the index() method that is available for lists. Here’s an example:

my_list = [1, 2, 3, 4, 5]
index = my_list.index(3)
print(index)  # Output: 2

In this example, we first define a list my_list containing integers from 1 to 5. We then use the index() method of the list to find the index of the element 3, which is 2. The index() method returns the index of the first occurrence of the specified element in the list.

If the element is not found in the list, the index() method raises a ValueError exception. To avoid this, you can use a conditional check like so:

my_list = [1, 2, 3, 4, 5]
if 3 in my_list:
  index = my_list.index(3)
  print(index)  # Output: 2
else:
  print("Element not found in list")

In this example, we use an if condition to check if the element 3 is present in the list. If it is present, we get its index using index() method. If it is not present, we print a message saying that the element is not found in the list.

Tags: