How to find all occurrences of an element in a list

Bruce picture Bruce · Jun 9, 2011 · Viewed 478k times · Source

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

Answer

Sven Marnach picture Sven Marnach · Jun 9, 2011

You can use a list comprehension:

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