I have a list of values which I need to filter given the values in a list of booleans:
list_a = [1, 2, 4, 6]
filter = [True, False, True, False]
I generate a new filtered list with the following line:
filtered_list = [i for indx,i in enumerate(list_a) if filter[indx] == True]
which results in:
print filtered_list
[1,4]
The line works but looks (to me) a bit overkill and I was wondering if there was a simpler way to achieve the same.
Advices
Summary of two good advices given in the answers below:
1- Don't name a list filter
like I did because it is a built-in function.
2- Don't compare things to True
like I did with if filter[idx]==True..
since it's unnecessary. Just using if filter[idx]
is enough.
if filter[indx] == True
Do not use==
if you want to check for identity withTrue
, useis
. Anyway in this case the whole comparison is useless, you could simply useif filter[indx]
. Lastly: never use the name of a built-in as a variable/module name(I'm referring to the namefilter
). Using something likeincluded
, so that theif
reads nicely (if included[indx]
).