← Back to NumPy Course | Chapter 10: Boolean & Comparison | Lesson 5 of 6

np.logical_and/or/not

logical_and, logical_or and logical_not combine conditions element by element.

In this page:

  1. np.logical_and/or/not
Syntax
python
np.logical_and(a, b)
np.logical_or(a, b)
np.logical_not(a)

np.logical_and/or/not

These functions are the named versions of &, | and ~ for boolean arrays. They accept any array-like input and treat non-zero as True. np.logical_xor is also available for exclusive or.

Note: With the operators, remember to wrap each comparison in parentheses.

Example: np.logical_and/or/not

python
import numpy as np

a = np.array([1, 4, 7, 10, 13])
big = a > 5
even = a % 2 == 0
print(np.logical_and(big, even))
print(np.logical_or(big, even))
print(np.logical_not(big))

# Output:
# [False False False  True False]
# [False  True  True  True  True]
# [ True  True False False False]
Related Topics
Common Mistakes
  1. Using Python and or or on arrays
  2. Forgetting parentheses with & and |
  3. Applying ~ to non-boolean integers
Chapter Summary
  • logical_and equals &
  • logical_or equals |
  • logical_not equals ~
  • Combine masks to filter data
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.