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:
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.
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics