Combining 3 boolean masks in Python

bard picture bard · Nov 17, 2013 · Viewed 14.2k times · Source

I have 3 lists:

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

When I type

a or b or c

I want to get back a list that's

[True, True, True]

but I'm getting back

[True, False, True]

Any ideas on why? And how can I combine these masks?

Answer

jscs picture jscs · Nov 17, 2013

Your or operators are comparing the lists as entire objects, not their elements. Since a is not an empty list, it evaluates as true, and becomes the result of the or. b and c are not even evaluated.

To produce the logical OR of the three lists position-wise, you have to iterate over their contents and OR the values at each position. To convert a bunch of iterables into a list of their grouped elements, use zip(). To check if any element in an iterable is true (the OR of its entire contents), use any(). Do these two at once with a list comprehension:

mask = [any(tup) for tup in zip(a, b, c)]