np.logical_and(a, b) evaluates the truthiness of each element of a and b, 0 is falsy, any nonzero number is truthy, and combines them with logical AND, position by position, returning a boolean array. It behaves like the bitwise & operator when both inputs are already boolean arrays, but unlike &, it explicitly evaluates truthiness first, which matters for non-boolean numeric inputs where & would instead perform a genuine bitwise operation on the underlying integer representation.
1Understanding np.logical_and()
np.logical_and(a, b) evaluates the truthiness of each element of a and b, 0 is falsy, any nonzero number is truthy, and combines them with logical AND, position by position, returning a boolean array. It behaves like the bitwise & operator when both inputs are already boolean arrays, but unlike &, it explicitly evaluates truthiness first, which matters for non-boolean numeric inputs where & would instead perform a genuine bitwise operation on the underlying integer representation.
For boolean arrays specifically, & and np.logical_and() give the same result, but for non-boolean numeric arrays, & performs actual bitwise AND on the integer bits, which is a very different operation from logical_and()'s truthiness-based combination — prefer logical_and(), or convert to bool first, when working with non-boolean data.
import numpy as np
a = np.array([True, True, False, False])
b = np.array([True, False, True, False])
print(np.logical_and(a, b))2Practical Example
Here is a real-world application of np.logical_and() showing how it is used in production NumPy code.
import numpy as np
arr = np.array([5, 10, 15, 20])
result = np.logical_and(arr > 5, arr < 20)
print(result)3Best Practices
Follow these guidelines when working with np.logical_and():
1. Use & between two boolean arrays for combining conditions, since it's more concise and produces the same result as logical_and() in that specific case
2. Use np.logical_and() explicitly, or convert to bool first, rather than & when the inputs might not already be boolean arrays
3. Remember Python's plain and/or keywords don't work element-wise on arrays at all — always use the bitwise operators or the logical_ functions instead
Tip: For boolean arrays specifically, & and np.logical_and() give the same result, but for non-boolean numeric arrays, & performs actual bitwise AND on the integer bits, which is a very different operation from logical_and()'s truthiness-based combination — prefer logical_and(), or convert to bool first, when working with non-boolean data.
import numpy as np
a = np.array([True, True, False, False])
b = np.array([True, False, True, False])
print(np.logical_and(a, b))