Given a list and a bitmask, how do I return the values at the indices that are True?

Kit picture Kit · Aug 24, 2010 · Viewed 7.5k times · Source

I start with the following list s and bitmask b:

s = ['baa', 'baa', 'black', 'sheep', 'have', 'you', 'any', 'wool']
b = [1, 0, 0, 0, 1, 1, 1, 0] # or any iterable with boolean values

How do I write some function apply_bitmask(s, b) so that it returns

['baa', 'have', 'you', 'any']

Answer

user395760 picture user395760 · Aug 24, 2010

Python 3.1 itertools.compress (or Python 2.7's if you haven't upgraded yet) does exactly that (the list comprehension is a real close second):

import itertools
filtered = itertools.compress(s, b)

Note that this produces an iterator, not a list. Saves memory, but if you need to iterate it several times or use indices, you can always use list(itertools.compress(s, b)). Still shorter.