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?
Asked
Active
Viewed 40 times
-1

karan_thakkar
- 9
- 1
-
Can you share the code where you are trying this task? – Kostas Mar 28 '21 at 06:37
-
Possible duplicate of https://stackoverflow.com/questions/6294179/how-to-find-all-occurrences-of-an-element-in-a-list – Simon Mar 28 '21 at 06:41
1 Answers
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