NumPy: Test whether any of the elements of a given array is non-zero
NumPy: Basic Exercise-4 with Solution
Write a NumPy program to test if any of the elements of a given array are non-zero.
Sample Solution :
Python Code :
# Importing the NumPy library with an alias 'np'
import numpy as np
# Creating a NumPy array 'x' containing elements 1, 0, 0, and 0
x = np.array([1, 0, 0, 0])
# Printing the original array 'x'
print("Original array:")
print(x)
# Checking if any element in the array 'x' is non-zero and printing the result
print("Test whether any of the elements of a given array is non-zero:")
print(np.any(x))
# Reassigning array 'x' to a new array containing all elements as zero
x = np.array([0, 0, 0, 0])
# Printing the new array 'x'
print("Original array:")
print(x)
# Checking if any element in the updated array 'x' is non-zero and printing the result
print("Test whether any of the elements of a given array is non-zero:")
print(np.any(x))
Sample Output:
Original array: [1 0 0 0] Test whether any of the elements of a given array is non-zero: True Original array: [0 0 0 0] Test whether any of the elements of a given array is non-zero: False
Explanation:
In the above code –
x = np.array([1, 0, 0, 0]): This line creates a NumPy array 'x' with the elements 1, 0, 0, and 0.
print(np.any(x)): This line uses the np.any() function to test if any elements in the array 'x' are non-zero (i.e., not equal to zero). In this case, the first element is non-zero, so the function returns True.
x = np.array([0, 0, 0, 0]): This line creates a new NumPy array 'x' with all elements equal to 0.
print(np.any(x)): This line uses the np.any() function again to test if any elements in the new array 'x' are non-zero. In this case, all elements are zero, so the function returns False.
Pictorial Presentation:
Python-Numpy Code Editor:
Previous: Test whether none of the elements of a given array is zero.
Next: Test a given array element-wise for finiteness (not infinity or not a Number).
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