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

1. Using enumerate() function

To get the index of all occurrences of an element in a list, you can use the built-in function enumerate(). It was introduced to solve the loop counter problem and can be used as follows:

Download  Run Code

 
To get the list of all indices at once, use list comprehension with enumerate function:

Download  Run Code

2. Using range() function

Alternatively, you can use the range() function to get the list of all valid indices and then match the corresponding value present at each index with the given item.

Download  Run Code

3. Using itertools module

Another approach is to use the count() function in itertools, which creates an iterator for efficient looping to return evenly spaced values starting with the given number. You can use it with the zip() function to add sequence numbers in the following manner.

Download  Run Code

4. Using more_itertools module

The more-itertools library provides elegant routines to work with Python iterables. You can use the more_itertools.locate function that yields the index of each item in iterable for which satisfies the given predicate. Following is a simple example demonstrating usage of this function:

Download Code

5. Using NumPy Library

Finally, if you happen to be using NumPy already and need all indexes, you may use the numpy.where() function.

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