np.logical_not(arr) evaluates each element's truthiness and flips it, returning True where the original was falsy and False where it was truthy — for a boolean array, this is equivalent to the ~ operator, but for non-boolean numeric arrays, logical_not() explicitly checks truthiness, 0 is falsy, anything else is truthy, rather than performing a bitwise complement of the number's bits, which is what ~ would actually do.
1Understanding np.logical_not()
np.logical_not(arr) evaluates each element's truthiness and flips it, returning True where the original was falsy and False where it was truthy — for a boolean array, this is equivalent to the ~ operator, but for non-boolean numeric arrays, logical_not() explicitly checks truthiness, 0 is falsy, anything else is truthy, rather than performing a bitwise complement of the number's bits, which is what ~ would actually do.
For a boolean array, ~arr and np.logical_not(arr) give the same result, but for a numeric integer array, ~ performs a genuine bitwise complement, flipping every bit including the sign bit for signed integers, a very different operation from logical negation — be careful applying ~ to anything that isn't already a proper boolean array.
import numpy as np
arr = np.array([True, False, True])
print(np.logical_not(arr))2Practical Example
Here is a real-world application of np.logical_not() showing how it is used in production NumPy code.
import numpy as np
arr = np.array([1, 0, 5, 0, -3])
print(np.logical_not(arr))3Best Practices
Follow these guidelines when working with np.logical_not():
1. Use ~ for negating boolean arrays/conditions, since it's more concise and equivalent to logical_not() in that specific case
2. Use np.logical_not() explicitly, or convert to bool first, rather than ~ on non-boolean numeric arrays, to avoid an unintended bitwise complement
3. Combine logical_not() with a condition to select everything that does not match a filter, as an alternative to inverting the comparison operator directly
Tip: For a boolean array, ~arr and np.logical_not(arr) give the same result, but for a numeric integer array, ~ performs a genuine bitwise complement, flipping every bit including the sign bit for signed integers, a very different operation from logical negation — be careful applying ~ to anything that isn't already a proper boolean array.
import numpy as np
arr = np.array([True, False, True])
print(np.logical_not(arr))