# NumPy All: Understanding np.all()

The `np.all()` function tests whether all elements in a NumPy array evaluate to true:

``````np.all(np.array([[1, 1], [1, 1]]))

# Expected result
# True``````

Notice the input can have arbitrary shape and the data type does not have to be boolean (it just has to be truthy). If any of the elements don’t evaluate to true, the function returns false:

``````np.all(np.array([[0, 1], [1, 1]]))

# Expected result
# False``````

We can also use the optional `axis` argument to make `np.all()` a reducing operation. Say we want to know which rows in a matrix have elements that all evaluate to true. We can do that by passing in `axis=-1`:

``````np.all(np.ones((2, 3)), axis=-1)

# Expected result
# array([ True,  True])``````

In the above example, there are two rows and for each of them, all elements evaluate to true. The `-1` value here is shorthand for “the last axis”.

And that’s it! NumPy also has a function called `np.any()` which has the same API as `np.all()` but returns true when any of the elements evaluate to true.

Connect

Contact

ben [at] sparrow [dot] dev

Email List