How to find all occurrences of an element in a list?


Question

index() will just give the first occurrence of an item in a list. Is there a neat trick which returns all indices in a list?

1
302
3/24/2016 2:41:06 PM

Accepted Answer

You can use a list comprehension:

indices = [i for i, x in enumerate(my_list) if x == "whatever"]
435
6/9/2011 2:13:57 PM

While not a solution for lists directly, numpy really shines for this sort of thing:

import numpy as np
values = np.array([1,2,3,1,2,4,5,6,3,2,1])
searchval = 3
ii = np.where(values == searchval)[0]

returns:

ii ==>array([2, 8])

This can be significantly faster for lists (arrays) with a large number of elements vs some of the other solutions.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon