Home > Enterprise >  How to find the order number of item inside of a list (have duplicates)
How to find the order number of item inside of a list (have duplicates)

Time:12-08

I wanna to find the order number (index number) of the item in a list, If this list looks like this

lst = ['a', 'v', 'c', 'a', 'b']

I wanna get the order number of item 'a', then the ideal output will be 0,3.

I have tried lst.index('a') but it only returns0

Any help would be really appreciated!

CodePudding user response:

This should be the easiest way to do this:

lst = ['a', 'v', 'c', 'a', 'b']
indices = []

for i in range(len(lst)):
    if lst[i] == 'a':
       indices.append(i)

print(indices)

CodePudding user response:

Here's how to do it with enumerate and a simple list comprehension:

>>> lst = ['a', 'v', 'c', 'a', 'b']
>>> [i for i, c in enumerate(lst) if c == 'a']
[0, 3]
  • Related