0

If you have a list with repeated elements, as below, how do you get the indices for each occurrence of that element?

Here's my example.

'''

listy = ["apples", "oranges", "apples", "bananas", "apples", "bananas"]

print (listy.index("bananas"))

'''

You can see it only will yield one result - 3, which is correct, but it is only one of the banana elements in the list.

What if you wanted to find the indices of all the others for any of the elements? Is there a way to do it?

Will
  • 45
  • 1
  • 5
  • 1
    Does this answer your question: https://thispointer.com/python-how-to-find-all-indexes-of-an-item-in-a-list/#:~:text=Find%20all%20indices%20of%20an%20item%20in%20list%20using%20list.&text=So%2C%20to%20find%20other%20occurrences,item%20in%20given%20list%20i.e. – Sushil Oct 22 '20 at 03:24
  • 2
    Does this answer your question? [How to find all occurrences of an element in a list](https://stackoverflow.com/questions/6294179/how-to-find-all-occurrences-of-an-element-in-a-list) – Michael Szczesny Oct 22 '20 at 03:27

3 Answers3

1

If your list keeps changing you can make a function which checks the index at the instant you require.

find_instance = lambda ele,lst : [i for i,j in enumerate(lst) if j==ele]
# To get indexes
find_instance('bananas', listy)

If your list is static, you can use defaultdict to store the index and get your index from it. It will be faster because it wont iterate the list everytime you require index.

from collections import defaultdict
my_indexes = defaultdict(list)
for i, j in enumerate(listy):
    my_indexes[j].append(i)
# To get indexes
print(my_indexes['bananas'])
PaxPrz
  • 1,778
  • 1
  • 13
  • 29
1

As an academic exercise:

listy = ["apples", "oranges", "apples", "bananas", "apples", "bananas"]

d = {k:[] for k in set(listy)}
for i,e in enumerate(listy):
   d[e].append(i)

print(d)

print('bananas', d['bananas'])

Output

{'oranges': [1], 'bananas': [3, 5], 'apples': [0, 2, 4]}
bananas [3, 5]
Mike67
  • 11,175
  • 2
  • 7
  • 15
0

All good answers. Thank you!

I knew it wasn't a hard question, but still got stuck on it.

Sometimes it is nice just to have a bit more to think about to jar one's thinking. :)

Will
  • 45
  • 1
  • 5