Difference between numpy.logical_and and &

user3821012 picture user3821012 · Oct 28, 2015 · Viewed 14.1k times · Source

I'm trying to use the logical_and of two or more numpy arrays. I know numpy has the function logical_and(), but I find the simple operator & returns the same results and are potentially easier to use.

For example, consider three numpy arrays a, b, and c. Is np.logical_and(a, np.logical_and(b,c)) equivalent to a & b & c?

If they are (more or less) equivalent, what's the advantage of using logical_and()?

Answer

Terry Brown picture Terry Brown · Jun 27, 2017

@user1121588 answered most of this in a comment, but to answer fully...

"Bitwise and" (&) behaves much the same as logical_and on boolean arrays, but it doesn't convey the intent as well as using logical_and, and raises the possibility of getting misleading answers in non-trivial cases (packed or sparse arrays, maybe).

To use logical_and on multiple arrays, do:

np.logical_and.reduce([a, b, c])

where the argument is a list of as many arrays as you wish to logical_and together. They should all be the same shape.