Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find all occurrences of an element in a list

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?

like image 451
Bruce Avatar asked Jun 09 '11 14:06

Bruce


People also ask

Which method finds the list of all occurrences in Python?

Use List Comprehension and the enumerate() Function to Get the Indices of All Occurrences of an Item in A List. Another way to find the indices of all the occurrences of a particular item is to use list comprehension.

How do you find out how many times an element is in a list?

The count() method returns the number of times element appears in the list.


1 Answers

You can use a list comprehension:

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. We filter down to all x that match our criterion, and select the indices i of these elements.

like image 124
Sven Marnach Avatar answered Sep 28 '22 23:09

Sven Marnach