Skip to main content

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

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

Here's a step-by-step tutorial on how to find the index of an element in a list in Python.

  1. First, create a list containing elements. For example:
my_list = [10, 20, 30, 40, 50]
  1. Next, choose the element for which you want to find the index. For example, let's say we want to find the index of the element 30 in my_list.

  2. Use the index() function to find the index of the element in the list. The index() function returns the index of the first occurrence of the specified element. For example:

index = my_list.index(30)
  1. The index variable now holds the index of the element 30 in the list. You can print it to see the result:
print(index)

Output: 2

  1. It's important to note that if the element is not found in the list, a ValueError will be raised. You can handle this exception using a try-except block:
try:
index = my_list.index(60)
print(index)
except ValueError:
print("Element not found in the list.")

Output: Element not found in the list.

  1. If there are multiple occurrences of the element in the list, the index() function will return the index of the first occurrence. To find the index of all occurrences, you can use a loop:
my_list = [10, 20, 30, 20, 40, 50]
element = 20

indices = []
for i in range(len(my_list)):
if my_list[i] == element:
indices.append(i)

print(indices)

Output: [1, 3]

  1. Another way to get the indices of all occurrences of an element is to use a list comprehension:
my_list = [10, 20, 30, 20, 40, 50]
element = 20

indices = [i for i in range(len(my_list)) if my_list[i] == element]

print(indices)

Output: [1, 3]

That's it! You now know how to find the index of an element in a list in Python.