Without an axis argument, np.all(arr) collapses the entire array into a single True/False, mirroring Python's built-in all() but vectorized and axis-aware for multi-dimensional arrays. With an axis specified, it instead returns a boolean array, one value per remaining position, indicating whether every element along that collapsed axis was truthy. It's commonly combined with a comparison, like checking that every element is greater than 0, to check a condition holds across an entire array or specific rows/columns.
1Understanding np.all()
Without an axis argument, np.all(arr) collapses the entire array into a single True/False, mirroring Python's built-in all() but vectorized and axis-aware for multi-dimensional arrays. With an axis specified, it instead returns a boolean array, one value per remaining position, indicating whether every element along that collapsed axis was truthy. It's commonly combined with a comparison, like checking that every element is greater than 0, to check a condition holds across an entire array or specific rows/columns.
Use a comparison inside np.all(), like np.all(arr == arr[0]), to check whether every element in an array equals a specific value, or np.array_equal() to compare two whole arrays for exact equality, rather than looping manually.
import numpy as np
arr = np.array([1, 2, 3, 4])
print(np.all(arr > 0))2Practical Example
Here is a real-world application of np.all() showing how it is used in production NumPy code.
import numpy as np
matrix = np.array([[1, 2], [3, -4]])
print(np.all(matrix > 0, axis=1))3Best Practices
Follow these guidelines when working with np.all():
1. Combine np.all() with a comparison to vectorize a condition check across an entire array or axis, instead of looping
2. Specify the axis argument explicitly on multi-dimensional data to check a condition per-row or per-column, rather than only for the whole array
3. Use np.array_equal(a, b) instead of np.all(a == b) when comparing two whole arrays, since array_equal() also correctly handles differing shapes
Tip: Use a comparison inside np.all(), like np.all(arr == arr[0]), to check whether every element in an array equals a specific value, or np.array_equal() to compare two whole arrays for exact equality, rather than looping manually.
import numpy as np
arr = np.array([1, 2, 3, 4])
print(np.all(arr > 0))