6

How can I use boolean inddex arrays to filter a list without using numpy?

For example:

>>> l = ['a','b','c']
>>> b = [True,False,False]
>>> l[b]

The result should be:

['a']

I know numpy support it but want to know how to solve in Python.

>>> import numpy as np
>>> l = np.array(['a','b','c'])
>>> b = np.array([True,False,False])
>>> l[b]
array(['a'], 
      dtype='|S1')
0

3 Answers 3

11

Python does not support boolean indexing but the itertools.compress function does exactly what you want. It return an iterator with means you need to use the list constructor to return a list.

>>> from itertools import compress
>>> l = ['a', 'b', 'c']
>>> b = [True, False, False]
>>> list(compress(l, b))
['a']
Sign up to request clarification or add additional context in comments.

Comments

5
[a for a, t in zip(l, b) if t]
# => ["a"]

A bit more efficient, use iterator version:

from itertools import izip
[a for a, t in izip(l, b) if t]
# => ["a"]

EDIT: user3100115's version is nicer.

Comments

1

Using enumerate

l = ['a','b','c']
b = [True,False,False]

res = [item for i, item in enumerate(l) if b[i]]

print(res)

gives

['a']

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.