w3resource

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

NumPy: Array Object Exercise-23 with Solution

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.

Python-Numpy Code Editor:

Previous: Write a NumPy program to find the union of two arrays. Union will return the unique, sorted array of values that are in either of the two input arrays.
Next: Write a NumPy program to test whether any array element along a given axis evaluates to True.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-exercises/numpy/python-numpy-exercise-23.php