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

Comparison operators on arrays

Comparing arrays with > < == gives back an array of True and False, one answer per element.
Syntax
python
arr == value
arr != value
arr > value
arr <= value

Comparison operators on arrays

Comparison operators (==, !=, <, <=, >, >=) are applied element-wise and return boolean arrays. These masks can be summed to count matches, since True counts as 1. To compare whole arrays for equality use np.array_equal or np.allclose.

Note: (a > 3).sum() counts how many elements are greater than 3.

Example: Comparison operators on arrays

python
import numpy as np

a = np.array([1, 5, 3, 8])
print(a > 3)
print((a > 3).sum())
print(a == np.array([1, 0, 3, 0]))
print(np.array_equal(a, a.copy()))

# Output:
# [False  True False  True]
# 2
# [ True False  True False]
# True
Related Topics
Common Mistakes
  1. Using == on arrays inside an if statement, which raises an ambiguity error
  2. Comparing floats with == instead of allclose
  3. Forgetting the result is an array
Chapter Summary
  • Comparisons return boolean arrays
  • True counts as 1 when summed
  • Use array_equal for whole-array equality
  • Use allclose for floats
🔒

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.