Search code examples
pythonarrayslistindexingenumerate

How can I find the index of each occurrence of an item in a python list?


I want to search through a python list and print out the index of each occurrence.

a = ['t','e','s','t']
a.index('t')

The above code only gives me the first occurrence's index.


Solution

  • You can use a list comprehension with enumerate:

    a = ['t','e','s','t']
    indices = [i for i, x in enumerate(a) if x == 't']
    

    Inside of the list comprehension, i is the current index and x is the value at that index.