Comparison operators on arrays
Comparing arrays with > < == gives back an array of True and False, one answer per element.
In this page:
Syntax
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
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
- Using == on arrays inside an if statement, which raises an ambiguity error
- Comparing floats with == instead of allclose
- 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: