In this tutorial, **you’ll learn how to use Python to find the list index of all occurrences of an element**. In many cases, Python makes it simple to find the first index of an element in a list. However, because Python lists can contain duplicate items, it can be helpful to find *all* of the indices of an element in a list.

By the end of this tutorial, you’ll have learned:

- How to find the indices of all occurences of an element in a Python list using:
- For loops,
- List comprehensions,
- NumPy, and
- more_itertools

- Which method is fastest

Let’s get started!

## How Python List Indices Work

Before diving into how to get the index positions of all elements in a Python list, let’s take a quick moment to understand how Python lists are indexed. Because Python lists are ordered container objects, their order remains unless it’s explicitly altered.

Python list indices start at 0 and continue through to the length of the list minus one. The image below shows how these list indices work in Python:

In the following section, you’ll learn how to use the list `.index()`

method to find the index of an element in the list.

## How the Python List Index Method Works

The Python list `.index()`

has three parameters:

- The element to search for,
- The index to begin searching at, and
- The index to search up to

The only required argument is the element to search for. By default, Python will search through the entire list, unless explicitly told otherwise.

Let’s take a look at how this method looks :

```
# The list.index() Method
list.index(
value=, # The value to search for
start=, # The index to start at
stop= # The index to end at
)
```

Let’s take a look at an example. We can load a list with different elements in it and find the index of the element using the `.index()`

method:

```
# Using the .index() Method
a_list = [1,2,3,4,1,2,1,2,3,4]
print(a_list.index(1))
# Returns: 0
```

In the example above, we applied the `.index()`

method on our list to find the index of the element `1`

. The method returned the value `0`

, meaning the item exists at the 0^{th} position. However, we know that the value exists multiple times in the list.

Why didn’t the method return more than the first index? This is how the method works. Even if an item exists more than once, only the first instance is returned.

In the following sections, you’ll learn how to get the index positions of all occurrences of an element in a list.

## How to Get Index of All Occurrences of Element in a Python List with a For Loop and Enumerate

One of the most basic ways to get the index positions of all occurrences of an element in a Python list is by using a for loop and the Python enumerate function. The enumerate function is used to iterate over an object and returns both the index and element.

Because of this, we can check whether the element matches the element we want to find. If it does, we can add the index position to another list. Let’s see how this works with an example:

```
# Using enumerate to Find Index Positions
a_list = [1,2,3,4,1,2,1,2,3,4]
def find_indices(list_to_check, item_to_find):
indices = []
for idx, value in enumerate(a_list):
if value == item_to_find:
indices.append(idx)
return indices
print(find_indices(a_list, 1))
# Returns: [0, 4, 6]
```

Let’s break down what we did here:

- We defined a function that takes a list and an element as input
- The function then loops over the retult of the
`enumerate()`

function - If the value of the item matches the item we’re looking for, the corresponding index is appended to the list
- Finally, the list of all indices is returned

## How to Get Index of All Occurrences of Element in a Python List with more_itertools

The built-in `more_itertools`

library comes with a number of helpful functions. One of these functions is the `locate()`

function that takes an iterable and a function to evaluate against.

In order to find the index positions of all elements matching an element, we can use a lambda function that simply checks if that item is equal to the item we want to check against.

Let’s take a look at an example:

```
# Using more_itertools to Find All Occurrences of an Element
from more_itertools import locate
a_list = [1,2,3,4,1,2,1,2,3,4]
def find_indices(list_to_check, item_to_find):
indices = locate(list_to_check, lambda x: x == item_to_find)
return list(indices)
print(find_indices(a_list, 1))
# Returns: [0, 4, 6]
```

Let’s break down what we did here:

- We defined a function that takes both a list and the element to search for
- The function uses the
`locate()`

function to use the list we want to search and a lambda function that checks if each item is equal to the value we’re searching for - Finally, the function returns a list of the result

## How to Get Index of All Occurrences of Element in a Python List with Numpy

NumPy makes the process of finding all index positions of an element in a list very easy and fast. This can be done by using the `where()`

function. The `where()`

function returns the index positions of all items in an array that match a given value.

Let’s take a look at an example:

```
# Using numpy to Find All Occurrences of an Element
import numpy as np
a_list = [1,2,3,4,1,2,1,2,3,4]
def find_indices(list_to_check, item_to_find):
array = np.array(list_to_check)
indices = np.where(array == item_to_find)[0]
return list(indices)
print(find_indices(a_list, 1))
# Returns: [0, 4, 6]
```

Let’s break down what we did here:

- We created a function that takes a list and an element to find
- The list is converted into a numpy array
- The
`where()`

function is used to evaluated the array against our item - We return the 0th index of that resulting array
- We convert that array to a list

## How to Get Index of All Occurrences of Element in a Python List with a List Comprehension

In this section, we’ll take a look at how to use a list comprehension to return a list of indices of an element in a list. This method works the same as the first method, the for loop, except it uses a list comprehension.

Let’s see how we can convert the for loop into a list comprehension:

```
# Using a List Comprehension to Find All Occurrences of an Element
a_list = [1,2,3,4,1,2,1,2,3,4]
def find_indices(list_to_check, item_to_find):
return [idx for idx, value in enumerate(list_to_check) if value == item_to_find]
print(find_indices(a_list, 1))
# Returns: [0, 4, 6]
```

The method shown above is much cleaner and easier to read than the for loop. In the next section, we’ll take a look at how these different methods compare in terms of speed.

## Which Method is Fastest To Get Index of All Occurrences of an Element in a Python List

The table below breaks down how long each method took to find the indices of all occurrences in a list of one hundred million elements:

Method | Time to execute |
---|---|

For loop and `enumerate()` | 4.97 seconds |

more_itertools `locate()` | 7.08 seconds |

numpy `where()` | 6.05 seconds |

List Comprehension and `enumerate()` | 4.69 seconds |

We can see that the list comprehension method was the fastest. Not only was this method the fastest, but it was very easy to read and required no additional packages.

## Conclusion

In this tutorial, you learned how to find the index positions of all occurrences of an element in a Python list. You learned how to do this using the Python `enumerate()`

function using both for loops and list comprehensions. You also learned how to use the numpy `where()`

function to do and the more_itertools `locate()`

function.

## Additional Resources

To learn more about related topics, check out the tutorials below: