215

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.

2
  • 5
    Just FYI, this is a common parallel computing primitive called stream compaction. (It's called a 'primitive' not because it is simple, but because it's used as a building block for many other parallel algorithms) Commented Sep 6, 2013 at 21:48
  • 3
    Some style notes: if filter[indx] == True Do not use == if you want to check for identity with True, use is. Anyway in this case the whole comparison is useless, you could simply use if filter[indx]. Lastly: never use the name of a built-in as a variable/module name(I'm referring to the name filter). Using something like included, so that the if reads nicely (if included[indx]).
    – Bakuriu
    Commented Sep 7, 2013 at 7:49

7 Answers 7

286

You're looking for itertools.compress:

>>> from itertools import compress
>>> list_a = [1, 2, 4, 6]
>>> fil = [True, False, True, False]
>>> list(compress(list_a, fil))
[1, 4]

Timing comparisons(py3.x):

>>> list_a = [1, 2, 4, 6]
>>> fil = [True, False, True, False]
>>> %timeit list(compress(list_a, fil))
100000 loops, best of 3: 2.58 us per loop
>>> %timeit [i for (i, v) in zip(list_a, fil) if v]  #winner
100000 loops, best of 3: 1.98 us per loop

>>> list_a = [1, 2, 4, 6]*100
>>> fil = [True, False, True, False]*100
>>> %timeit list(compress(list_a, fil))              #winner
10000 loops, best of 3: 24.3 us per loop
>>> %timeit [i for (i, v) in zip(list_a, fil) if v]
10000 loops, best of 3: 82 us per loop

>>> list_a = [1, 2, 4, 6]*10000
>>> fil = [True, False, True, False]*10000
>>> %timeit list(compress(list_a, fil))              #winner
1000 loops, best of 3: 1.66 ms per loop
>>> %timeit [i for (i, v) in zip(list_a, fil) if v] 
100 loops, best of 3: 7.65 ms per loop

Don't use filter as a variable name, it is a built-in function.

4
  • @Mehdi I find the Matlab way highly unintuitive, but I suppose it depends on what you are used to.
    – Ian Goldby
    Commented Sep 25, 2017 at 8:42
  • How can I select [2, 6] ?
    – Florent
    Commented May 30, 2018 at 21:03
  • I get it, list(compress(list_a, [not i for i in fill])) should return [2, 6]
    – Florent
    Commented May 30, 2018 at 21:10
  • 'list' object is not callable
    – logicbloke
    Commented Apr 3, 2021 at 8:55
74

Like so:

filtered_list = [i for (i, v) in zip(list_a, filter) if v]

Using zip is the pythonic way to iterate over multiple sequences in parallel, without needing any indexing. This assumes both sequences have the same length (zip stops after the shortest runs out). Using itertools for such a simple case is a bit overkill ...

One thing you do in your example you should really stop doing is comparing things to True, this is usually not necessary. Instead of if filter[idx]==True: ..., you can simply write if filter[idx]: ....

3
  • despite this does not have many upvotes, and this is not an accepted solution, why is this answer on the top of the list???
    – Tom
    Commented Aug 9, 2022 at 20:54
  • @Tom check the "sorted by" dropdown list just below the question. You might have it set to "trending (recent votes count more)" or "date modified/created" instead of "highest score" Commented Aug 12, 2022 at 11:22
  • ohhh! I see! now I see the option! thank you!
    – Tom
    Commented Aug 14, 2022 at 21:55
50

With numpy:

In [128]: list_a = np.array([1, 2, 4, 6])
In [129]: filter = np.array([True, False, True, False])
In [130]: list_a[filter]

Out[130]: array([1, 4])

or see Alex Szatmary's answer if list_a can be a numpy array but not filter

Numpy usually gives you a big speed boost as well

In [133]: list_a = [1, 2, 4, 6]*10000
In [134]: fil = [True, False, True, False]*10000
In [135]: list_a_np = np.array(list_a)
In [136]: fil_np = np.array(fil)

In [139]: %timeit list(itertools.compress(list_a, fil))
1000 loops, best of 3: 625 us per loop

In [140]: %timeit list_a_np[fil_np]
10000 loops, best of 3: 173 us per loop
1
  • 2
    Good point, I prefer using NumPy over list where possible. But if you need to use list anyway, you have (using NumPy solution) create np.array from both lists, use boolean indexing and finally converting array back to list with tolist() method. To be precise, you should include those objects creation into time comparison. Then, using itertools.compress will be still the fastest solution.
    – Nerxis
    Commented Jul 9, 2020 at 12:15
21

To do this using numpy, ie, if you have an array, a, instead of list_a:

a = np.array([1, 2, 4, 6])
my_filter = np.array([True, False, True, False], dtype=bool)
a[my_filter]
> array([1, 4])
1
  • 3
    If you turn my_filter into a boolean array, you can use direct boolean indexing, without the need for where. Commented Sep 6, 2013 at 21:10
7
filtered_list = [list_a[i] for i in range(len(list_a)) if filter[i]]
0

May be not so elegant, but I think this solution has simplier syntax. I renamed filter to filter_ to avoid conflict with the built in function:

list_a = [1, 2, 4, 6]
filter_ = [True, False, True, False]

Here the solution:

index = [i for i in range(len(filter_)) if filter_[i]]
list_a_filtered = [list_a[i] for i in index]

or in one line:

list_a_filtered = [list_a[i] for i in [j for j in range(len(filter_)) if filter_[j]]]
-4

With python 3 you can use list_a[filter] to get True values. To get False values use list_a[~filter]

2
  • 5
    With e.g. numpy.array, this works, but with built-in lists it doesn’t. Commented Oct 3, 2020 at 19:08
  • What happens when you try this with a list? Commented May 10, 2023 at 23:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.