Are there builtin functions for elementwise boolean operators over boolean lists?
Asked Answered
G

5

28

For example, if you have n lists of bools of the same length, then elementwise boolean AND should return another list of that length that has True in those positions where all the input lists have True, and False everywhere else.

It's pretty easy to write, i just would prefer to use a builtin if one exists (for the sake of standardization/readability).

Here's an implementation of elementwise AND:

def eAnd(*args):
    return [all(tuple) for tuple in zip(*args)]

example usage:

>>> eAnd([True, False, True, False, True], [True, True, False, False, True], [True, True, False, False, True])
[True, False, False, False, True]
Greenshank answered 5/5, 2010 at 3:36 Comment(0)
D
23

There is not a built-in way to do this. Generally speaking, list comprehensions and the like are how you do elementwise operations in Python.

Numpy does provide this (using &, for technical limitations) in its array type. Numpy arrays usually perform operations elementwise.

Deberadeberry answered 5/5, 2010 at 3:52 Comment(0)
F
21

Try:

[ x&y for (x,y) in zip(list_a, list_b)]

If you are dealing with really long lists, or some of your variables are / need to be numpy arrays, the equivalent numpy code would be:

list( np.array(list_a) & np.array(list_b) )

modify it based on your needs.

Ferment answered 11/6, 2014 at 15:15 Comment(4)
for me this seems really pythonic and you also don't have to import numpyBini
If at all possible, I'd still recommend numpy, though, as it is orders of magnitude faster, and the syntax is even easier to read: arr1 & arr2 gives you an array of the results.Cannes
@Zak: I concur, especially if list_a, list_b are long or are already numpy arrays. Otherwise you pay to convert them.Ferment
You can also use np.logical_and()Drennan
V
3

The numpy.all function does what you want, if you specify the dimension to collapse on:

>>> all([[True, False, True, False, True], [True, True, False, False, True], [True, True, False, False, True]], 0)
array([ True, False, False, False,  True], dtype=bool)
Voccola answered 4/6, 2014 at 16:12 Comment(1)
The all function you're referring to isn't a built-in function, though; that's numpy.all.Roveover
M
1

No, there are no such built-ins. Your method using zip and all / any is what I would use.

Maxi answered 5/5, 2010 at 3:40 Comment(0)
I
1

No, I don't believe there's any such function in the standard library... especially when it's so easy to write in terms of the functions that are provided.

Indignity answered 5/5, 2010 at 3:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.