Search code examples
pythonpython-3.xlistfor-loopenumerate

Using enumerate for "one-line for loops"


I have a list like

my_id = 3

Word IDs: [None, 0, 1, 2, 3, 3, 3, 4, None]

I want to make a list of all indexes in the above list that their corresponding value is equal to my_id

I want to write a one-line for loop. This is not working. Is there some way to write it as a "one-line for loop"?

My way:

list_of_word_ids = [i for enumerate(i,_id) in inputs if _id == id_word ]

My desired outputs in this case are

4, 5, 6


Solution

  • enumerate returns a tuple with its counter. You can unpack the tuple and check if seconds value is equal to my_id

    Word_IDs= [None, 0, 1, 2, 3, 3, 3, 4, None]
    
    list_of_word_ids = [i for i,j in enumerate(Word_IDs) if j == my_id]