Search code snippets, questions, articles...

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']

print(indexes)
# -> [1, 3, 5]
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place.

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?
0 Comments