 GeeksforGeeks App
Open App Browser
Continue

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

Given a list, the task is to write a Python Program to get the indices of all occurrences of an element in a list.

## Find index of all occurrences of an item using  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)

## Find index of all occurrences of an item 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]`

## 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]`

## 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

Step-by-step algorithm:

1. Import the pandas library
2. Initialize the list “my_list” and the item whose indices are to be found
3. Create a pandas dataframe “df” with a column “col” containing the elements of the list
4. Filter the dataframe rows based on the value of the “col” column matching the given item
5. Get the indices of the filtered rows
6. Convert the pandas index object to a list
7. 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.

My Personal Notes arrow_drop_up