Find all indexes of an item in a list using python

To get all the occurrences of an item inside a list and get all the indexes, you can use the code examples described here.

#define the list
my_list = ['a', 'b', 'c', 'b', 'd', 'b', 'a']

#get all indexed of 'b'
indexes = [index for index, item in enumerate(my_list) if item == 'b']

# -> [1, 3, 5]

We are perfoming following taks using above code snippet.

1. Created a python list variable named my_list that contains multiple items.

2. Passing my_list variable to enumerate() function and creating for loop using this.

3. Checking inside the loop if the item is equal to 'b' and returning index if condition satisfied.

4. Printing indexes list. If the item does not exist in the list, it will print a blank array.

Was this helpful?