How to mask a list using boolean values from another list

I think the easiest way is to use numpy:

import numpy as np
>>> x = [True, False, True, False]
>>> y = ['a', 'b', 'c', 'd']
>>> np.array(y)[x]
array(['a', 'c'], dtype='<U1')

Without numpy, You could also enumerate in a list comprehension:

>>> [i for idx, i in enumerate(y) if x[idx]]
['a', 'c']

You can use zip and a list comprehension to perform a filter operation on y based on corresponding truth values in x:

x = [True, False, True, False]
y = ["a", "b", "c", "d"]

print([b for a, b in zip(x, y) if a])

Output:

['a', 'c']

itertools.compress also does this:

>>> from itertools import compress
>>> x = [True, False, True, False]
>>> y = ["a", "b", "c", "d"]
>>> list(compress(y, x))
['a', 'c']

Tags:

Python

List