Find Index of All Matching Elements in List in Python (3 Examples)

 

Hi! This tutorial will show you how to determine the index of all matching elements in lists in the Python programming language.

Here is an overview:

Let’s jump into the Python code!

 

Create Sample List

We will here create the sample Python list of integers that we will use in the examples in this tutorial.

So, in your Python programming IDE, run the code below to create the sample list:

my_list = [1, 2, 3, 4, 2, 5, 2]
 
print(my_list)
 
# [1, 2, 3, 4, 2, 5, 2]
 
print(type(my_list))
 
# <class 'list'>

Now that we have created the sample list, we will examine three ways to return the indexes of all matching elements in the list.

The target element variable, the indexes of whose matching elements we will find, is defined below:

target_element = 2

 

Example 1: Determine Index of All Matching Elements in List Using for Loop & enumerate() Function

In this first example, we will use a for loop along with the enumerate() function to get the index of all the matching elements in the list:

matching_indices = []
 
for i,e in enumerate(my_list):
  if e == target_element:
    matching_indices.append(i)
 
print(matching_indices)
 
# [1, 4, 6]
 
print(type(matching_indices))
 
# <class 'list'>

Here, an empty list called matching_indices is created to store the indices of elements that match the target element.

The for loop iterates over the elements of my_list using the enumerate() function, which provides both the index i and element e at each iteration as a tuple.

It checks if the current element e is equal to target_element. If there is a match, the current index i is appended to matching_indices.

Finally, the list of matching indices is printed using the print() function.
 

Example 2: Determine Index of All Matching Elements in List Using List Comprehension

In this second example, we will use list comprehension to obtain the index of all matching elements in the list:

matching_indices = [i for i in range(len(my_list)) if my_list[i] == target_element]
 
print(matching_indices)
 
# [1, 4, 6]
 
print(type(matching_indices))
 
# <class 'list'>

In the above example, we used a list comprehension to find the indices of all elements in my_list that match target_element.

The list comprehension creates a new list called matching_indices by iterating over the indices of my_list using the range() function.

For each index i, it checks if the element at that index my_list[i] is equal to target_element. If there is a match, the index i is included in matching_indices.

Finally, the resulting list of matching indices is printed to the console using the print() function.
 

Example 3: Determine Index of All Matching Elements in List Using NumPy

For this final example, we will need to install and import Python’s NumPy library, if you do not already have it installed and imported:

# install NumPy
pip install numpy
 
# import NumPy
import numpy as np

With NumPy installed and imported, let us now use some of it available function to get the index of all matching elements in the list:

my_array = np.array(my_list)
 
matching_indices = np.where(my_array == target_element)[0]
 
print(matching_indices)
 
# [1 4 6]
 
print(type(matching_indices))
 
# <class 'numpy.ndarray'>

In this example, we first convert my_list into a NumPy array called my_array using the np.array() function.

Then, we use the np.where() function to search for elements in my_array that are equal to target_element.

The np.where() function returns a tuple with indices where the condition is true, and in this case, we access the first element of the tuple [0] to retrieve the matching indices.

Finally, the resulting matching_indices is printed to the console.
 

Video, Further Resources & Summary

Do you need more explanations on how to find the index of all matching elements in a list in Python? Then you should have a look at the following YouTube video of the Statistics Globe YouTube channel.

In the video, we explain in some more detail how to find the index of all matching elements in a list in Python.

 

The YouTube video will be added soon.

 

Furthermore, I encourage you to check out other interesting Python list tutorials on Statistics Globe, starting with these ones:

This post has shown, using three examples, how to find the index of all matching elements in a list in Python. Your use case will determine which of the solutions to adopt.

I do hope you found this tutorial helpful! In case you have further questions, you may leave a comment below.

 

R & Python Expert Ifeanyi Idiaye

This page was created in collaboration with Ifeanyi Idiaye. You might check out Ifeanyi’s personal author page to read more about his academic background and the other articles he has written for the Statistics Globe website.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


2 Comments. Leave new

  • Hello what if the the target element is actually a list of elements?
    indices_rear_angles_in_theta=[ index for (index, item) in enumerate(angle) if item ==8]
    it works fine for this but when I change it for a list I don’t get correct indices.
    indices_rear_angles_in_theta=[ index for (index, item) in enumerate(angle) if item in angle ]

    Reply
    • Hello Saima,

      With a slight modification in list comprehension, you can also find the matching elements indices based on a target list. See the code below please.

      list_a = [1, 2, 3, 4, 5]
      target_list = [4, 5, 6, 7, 8]
       
      matching_indexes = [index for index, element in enumerate(list_a) if element in target_list]
      matching_indexes
      # [3, 4]

      Best,
      Cansu

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Top