np.logical_or(a, b) mirrors np.logical_and() exactly, but combines truthiness with OR instead of AND, returning True at each position where at least one of the two inputs is truthy. Like logical_and(), it agrees with the bitwise | operator for genuinely boolean arrays, but diverges for non-boolean numeric arrays, where | performs actual bitwise OR on the integer bits instead of a truthiness-based combination.
1Understanding np.logical_or()
np.logical_or(a, b) mirrors np.logical_and() exactly, but combines truthiness with OR instead of AND, returning True at each position where at least one of the two inputs is truthy. Like logical_and(), it agrees with the bitwise | operator for genuinely boolean arrays, but diverges for non-boolean numeric arrays, where | performs actual bitwise OR on the integer bits instead of a truthiness-based combination.
Combine several conditions with | when you want to select elements matching any one of multiple criteria — remember each condition needs its own parentheses due to operator precedence.
import numpy as np
a = np.array([True, True, False, False])
b = np.array([True, False, True, False])
print(np.logical_or(a, b))2Practical Example
Here is a real-world application of np.logical_or() showing how it is used in production NumPy code.
import numpy as np
arr = np.array([-5, 10, 50, 150])
outliers = arr[(arr < 0) | (arr > 100)]
print(outliers)3Best Practices
Follow these guidelines when working with np.logical_or():
1. Use | between two boolean condition arrays for combining alternatives, since it's more concise and equivalent to logical_or() in that specific case
2. Wrap each condition in parentheses when combining multiple comparisons with |, since | has higher precedence than comparison operators in Python
3. Use np.logical_or() explicitly, or convert to bool first, rather than | when the inputs might not already be boolean arrays
Tip: Combine several conditions with | when you want to select elements matching any one of multiple criteria — remember each condition needs its own parentheses due to operator precedence.
import numpy as np
a = np.array([True, True, False, False])
b = np.array([True, False, True, False])
print(np.logical_or(a, b))