Open In App

Python – Get the indices of all occurrences of an element in a list

Last Updated : 18 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will be going to understand how to get all the indices of an element in a list in Python and we will also cover a few of the best approaches to do so.

Example

Input: my_list = [1, 2, 3, 1, 5, 4]
item = 1
Output: 0,3
Explanation: The output contains all the index of element 1 in the my_list.

Find List Index of All Occurrences of an Element

Below are the topics that we will cover in this article:

Find the Index of All Occurrences of an Item Using a Loop

This method to get the indices of all occurrences of an element in a list. Here we use a for-loop to iterate through each element in the original list.

Python3




# initialize a list
my_list = [1, 2, 3, 1, 5, 4]
 
# find length of the list
list_size = len(my_list)
 
# declare for loop
for itr in range(list_size):
 
      # check the condition
    if(my_list[itr] == 1):
 
          # print the indices
        print(itr)


Output

0
3


Time Complexity: O(n)
Space Complexity: O(1)

Get Index of All Occurrences of Element Using List Comprehension

This is a simple method to get the indices of all occurrences of an element in a list using list comprehension. Here we use a list comprehension to iterate through each element in the original list.

Python3




# initialize a list
my_list = [1, 2, 3, 1, 5, 4]
item = 1
 
indices = [i for i in range(len(my_list)) if my_list[i] == item]
 
# print the indices
print(indices)


Output

[0, 3]


Time Complexity: O(n)
Auxiliary Space: O(1)

Find Index of All Occurrences of an Item Using Enumerate() Function

Instead of using for-loop we can use enumerate function. This function adds a counter to an iterable and returns the enumerated object. For this, we will create a list and then we will create enumerate function to get indices of all occurrences of an element in a list

Python3




# initialize a list
my_list = [1, 2, 3, 1, 5, 4
indices = [ind for ind, ele in enumerate(my_list) if ele == 1]
 
# print the indices
print(indices) 


Time Complexity: O(n)
Space Complexity: O(n)

Find index of All Occurrences of an Item Using Itertools Module

An itertools module is a memory-efficient tool that is useful by itself or in combination, so for this, we will use count() methods from this module which will return an iterator of evenly spaced values from the start value. For this, we will create a list, and then using comprehension with zip() we will get indices of all occurrences of an element in a list. 

Python3




# import count method from itertools
from itertools import count 
 
# initialize a list
my_list = [1, 2, 3, 1, 5, 4]
indices = [ind for ind,
           ele in zip(count(),
                      my_list) if ele == 1]
 
# print the indices
print(indices) 


Output

[0, 3]


Time Complexity: O(n)
Space Complexity: O(n)

Get the Indices of All Occurrences of an Element Using Numpy Library

NumPy is a general-purpose array-processing package, it provides convenient ways to use arrays in Python. For this, we will create an array using numpy.array() and then get all the indices of elements in an input array when the condition is satisfied using numpy.where() methods.

Python3




# import numpy module
import numpy 
 
# initialize a array
my_list = numpy.array([1, 2, 3, 1, 5, 4]) 
indices = numpy.where(my_list == 1)[0]
 
# display result
print(indices) 


Output :

[0, 3]

Time Complexity: O(n)
Space Complexity: O(n)

Get the indices of all occurrences of an element using the Python Dictionary

A dictionary called `indices` and a list named `my_list`. It then iterates through the elements in `my_list`, storing their indices in the dictionary `indices`. For each element encountered, if it’s already a key in the dictionary, the current index is appended to its list of indices; otherwise, a new key is created with the element and its index. Afterward, the code prints the indices of the value 1 in the list. As a result, the indices of the value 1 in `my_list` (0 and 3) are displayed when the code is executed.

Python3




indices = {}
 
# initialize a list
my_list = [1, 2, 3, 1, 5, 4]
 
for i in range(len(my_list)):
    if my_list[i] in indices.keys():
        indices[my_list[i]].append(i)
    else:
        indices[my_list[i]] = [i]
 
# print the indices
print(indices[1])


Output

[0, 3]


Get the Indices of All Occurrences of an Element Using the Panda Library

Import the pandas library then Initialize the list “my_list” and the item whose indices are to be found and create a pandas dataframe “df” with a column “col” containing the elements of the list. Filter the dataframe rows based on the value of the “col” column matching the given item.Get the indices of the filtered rows and then convert the pandas index object to a list and print the list of indices

Python3




import pandas as pd
 
my_list = [1, 2, 3, 1, 5, 4]
item = 1
 
df = pd.DataFrame({'col': my_list})
indices = df.index[df['col'] == item].tolist()
 
print(indices)


Output

[0, 3]


Time complexity: O(n), where n is the number of elements in the input list.This is because creating the pandas data frame takes O(n) time, and filtering the data frame takes O(n) time in the worst case. 

Auxiliary Space: O(n), where n is the number of elements in the input list. This is because creating the pandas data frame requires O(n) space to store the elements of the list.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads