w3resource

NumPy: Test whether all elements in an array evaluate to True


Test All Elements are True

Write a NumPy program to test if all elements in an array evaluate to True.
Note: 0 evaluates to False in python.

Pictorial Presentation:

Python NumPy: Test whether all elements in an array evaluate to True

Sample Solution:

Python Code:

# Importing the NumPy library with an alias 'np'
import numpy as np

# Checking if all elements along a specified axis evaluate to True or non-zero
print(np.all([[True,False],[True,True]]))  # Evaluates to False because at least one element in the array is False
print(np.all([[True,True],[True,True]]))   # Evaluates to True because all elements in the array are True

# Checking if all elements in an iterable evaluate to True or non-zero
print(np.all([10, 20, 0, -50]))   # Evaluates to False because 0 (which evaluates to False) is present in the list
print(np.all([10, 20, -50]))      # Evaluates to True because all elements in the list are non-zero and evaluate to True

Sample Output:

False                                                                  
True                                                                   
False                                                                  
True

Explanation:

In the above code –

print(np.all([[True,False],[True,True]])): np.all checks if all elements of the input array are True. In this case, there is a False value in the array, so the output is False.

print(np.all([[True,True],[True,True]])): np.all checks if all elements of the input array are True. In this case, all elements are True, so the output is True.

print(np.all([10, 20, 0, -50])): np.all checks if all elements of the input array are non-zero. In this case, there is a zero in the array, so the output is False.

print(np.all([10, 20, -50])): np.all checks if all elements of the input array are non-zero. In this case, all elements are non-zero, so the output is True.


For more Practice: Solve these Related Problems:

  • Use np.all to check if every element in a boolean array evaluates to True.
  • Convert a numeric array to boolean and test if all elements are nonzero.
  • Create a function that tests the truth value of an array along a specific axis.
  • Verify the all condition on an array containing mixed true (nonzero) and false (zero) values.

Go to:


PREV : Union of Two Arrays
NEXT : Test Any Element is True


Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.