Search code examples
pythonpython-3.xlistmasked-array

Filter elements from list based on True/False from another list


Is there an idiomatic way to mask elements of an array in vanilla Python 3? For example:

a = [True, False, True, False]
b = [2, 3, 5, 7]
b[a]

I was hoping b[a] would return [2, 5], but I get an error:

TypeError: list indices must be integers or slices, not list

In R, this works as I expected (using c() instead of [] to create the lists). I know NumPy has MaskedArray that can do this, I'm looking for an idiomatic way to do this in plain vanilla Python. Of course, I could use a loop and iterate through the mask list and the element list, but I'm hoping there's a more efficient way to mask elements using a higher level abstraction.


Solution

  • You can use itertools.compress:

    >>> from itertools import compress
    >>> a = [True, False, True, False]
    >>> b = [2, 3, 5, 7]
    
    
    >>> list(compress(b, a))
    [2, 5]
    

    Refer "itertools.compress()" document for more details