This post will discuss how to find the index of an element in a Python List.

1. Using list.index() function

The preferred, idiomatic way to find the index of an element in a list is using the index() function. This function is a built-in function in Python that returns the index of the first occurrence of a given element in the list. Here is an example of its usage:

Download  Run Code

 
The index() function raises ValueError if the element is not in the list. One way to handle this is by checking the presence of an element in the list using in operator, before calling the index() function:

Download  Run Code

 
Another way to handle ValueError is by wrapping the call to the index() function inside a try/except block for catching ValueError.

Download  Run Code

2. Using for loop

Another way to find the index of an element in a list is to use a for loop. The idea is to iterate over each element in the list using a for loop, and compare each element with the target value and if they match, we can keep track of the corresponding index and break out of the loop. Here is an example of how to achieve this using the enumerate() function, which returns an enumerate object that contains pairs of indexes and values from an iterable.

Download  Run Code

3. Finding index of all occurrences of the element

To get the index of all occurrences of the element in a list, we can use list comprehension along with the enumerate() function. For example:

Download  Run Code

That’s all about finding the index of an element in a list in Python.