-1

For example, if I have a list of words like ['to', 'be', 'or', 'not', 'to', 'be'], now for some reason in a for loop or in a function definition with list.index(value) method, I want to find all the indices of each word but when I reach up to 'to' word (2nd occurrence) it gives me an index of its first occurrence itself. How can I resolve this?

1 Answers1

1

A list comprehension solution might be:

lst = ['to', 'be', 'or', 'not', 'to', 'be']
{req_word: [idx for idx, word in enumerate(lst) if word == req_word] for req_word in set(lst)}

results in:

{'be': [1, 5], 'or': [2], 'to': [0, 4], 'not': [3]}

You can think of all other ways along the same lines as well but with index() you can find only one index although you can set occurrence number yourself.

Hamza
  • 5,373
  • 3
  • 28
  • 43