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.
- First, create a list containing elements. For example:
my_list = [10, 20, 30, 40, 50]
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
30inmy_list.Use the
index()function to find the index of the element in the list. Theindex()function returns the index of the first occurrence of the specified element. For example:
index = my_list.index(30)
- The
indexvariable now holds the index of the element30in the list. You can print it to see the result:
print(index)
Output: 2
- It's important to note that if the element is not found in the list, a
ValueErrorwill be raised. You can handle this exception using atry-exceptblock:
try:
index = my_list.index(60)
print(index)
except ValueError:
print("Element not found in the list.")
Output: Element not found in the list.
- 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]
- 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.