How to filter entries from a list based on a criteria and get the index in Python?

Question:

I have a list say list=[1,4,6,3,2,1,8] and I want to filter this list based on the condition that entry>3 and return the corresponding index.

So the output should be : [1,2,6] which corresponds to the values 4,6 and 8.

how to do this efficiently in Python?

Asked By: ELLA

||

Answers:

You can use a list comprehension with enumerate.

l = [1,4,6,3,2,1,8] # you should not overwrite the list builtin
res = [i for i, x in enumerate(l) if x > 3]
Answered By: Unmitigated
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.