Learn python – find index of all occurrences in list

In this situation, we need to use the 'for' loop. In this loop, we need to check all the elements and add their indices if this is the element we need.

def get_all_indexes(my_list, element):
    return [index for index, value in enumerate(my_list) if value == element]

fruits = ["apple", "pineapple", "orange", "apple", "grape", "lemon", "orange"]

print(f"Indexes for 'apple': {get_all_indexes(fruits, 'apple')}")
print(f"Indexes for 'banana': {get_all_indexes(fruits, 'banana')}")

Output:

Indexes for 'apple': [0, 3]
Indexes for 'banana': []
#python
menu 1
Roman Ivashchenko profile picture
Nov 24, 2020
by Roman Ivashchenko
Did it help you?
Yes !
No

Best related

Other by Roman Ivashchenko