Skip to content

Python find index of all occurrences in list

  • by

Use a list comprehension with enumeration to find an index of all occurrences in the list in Python.

indices = [i for i, x in enumerate(my_list) if x == "whatever"]

The iterator enumerate(my_list) yields pairs (index, item) for each item in the list. Using i, x as loop variable target unpacks these pairs into the index i and the list item x. then filter down to all x that match our criterion and select the indices i of these elements.

Source: stackoverflow.com

Python finds the index of all occurrences in the list example

Simple example code.

l = [1, 2, 3, 4, 3, 2, 5, 6, 7]

res = [i for i, val in enumerate(l) if val == 3]

print("index of 3:", res)

Output:

Python find index of all occurrences in list

Using numpy

import numpy as np

values = np.array([1, 2, 3, 1, 2, 4, 5, 6, 3, 2, 1])
searchval = 3
res = np.where(values == searchval)[0]

print(res)

Output: [2 8]

Using a for-loop to iterate through each element in the original list.

my_list = [1, 2, 3, 1, 5, 4]

for itr in range(len(my_list)):
if (my_list[itr] == 1):
# print the indices
print(itr)

Output:

0
3

Using list comprehension

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)

Using itertools module

from itertools import count 
 
my_list = [1, 2, 3, 1, 5, 4]
indices = [ind for ind,
           ele in zip(count(),
                      my_list) if ele == 1]

print(indices) 

Do comment if you have any doubts or suggestions on this Python index list topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading