Search code examples
pythonindicesenumerate

Returning unique indices for given value in python


I have a list where I need to extract index number of all elements based on given unique value.

If I apply:

test3 = ["P3","P35","P35","P3","P2"]
actual_state = "P3"
indexes = [n for n, x in enumerate(test3) if actual_state in x]

this returns:

[0, 1, 2, ,3]

But output should be:

[0, 3]

P3 exists in P35 as well, renaming P35 won't help since I have nested list with thousands of inputs, any advice how can I extract this in desired way ? Thanks.


Solution

  • Change in to ==, because in test substrings also:

    indexes = [n for n, x in enumerate(test3) if actual_state == x]
    print (indexes)
    [0, 3]