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

Question:

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.

Asked By: CoderDude

||

Answers:

Yes you can do it with enumerate

[x[0] for x in enumerate(a) if x[1]=='t']

Out[267]: [0, 3]
Answered By: BENY

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.

Answered By: iz_
def get_indices(my_list, item):
    result = []
    for i in range(len(my_list)):
        if my_list[i] == item:
            result.append(i)
    return result

Then try it out…

>>> get_indices(a, "t")
[0, 3]
Answered By: Simon Thomas

With enumerate inside list comprehension for t,

>>> list1 = ['t','e','s','t']
>>> all_index = [i for i, j in enumerate(list1) if j == 't']
>>> all_index

Output:

[0, 3]

With loop for all element,

list1 = ['t','e','s','t']
result = {}
for e in list1:
    result[e] = [i for i, j in enumerate(list1) if j == e]
print(result)

Output:

 {'s': [2], 'e': [1], 't': [0, 3]}
Answered By: Always Sunny