w3resource

NumPy: Check whether the numpy array is empty or not


Check if Array is Empty

Write a NumPy program to check whether the NumPy array is empty or not.

Pictorial Presentation:

Python NumPy: Check whether the numpy array is empty or not

Sample Solution:

Python Code:

# Importing the NumPy library and aliasing it as 'np'
import numpy as np

# Creating a NumPy array 'x' containing integers [2, 3]
x = np.array([2, 3])

# Creating an empty NumPy array 'y'
y = np.array([])

# Printing the size of array 'x'
# As 'x' contains 2 elements, its size is 2
print(x.size)

# Printing the size of array 'y'
# 'y' is an empty array, so its size is 0
print(y.size)

Sample Output:

2                                                                      
0

Explanation:

In the above code –

x = np.array([2, 3]): This line creates a NumPy array 'x' containing the integer values 2 and 3.

y = np.array([]): This line creates an empty NumPy array 'y'.

print(x.size): Print the size of array 'x' using the size attribute. In this case, the size is 2 since 'x' contains two elements.

print(y.size): Print the size of array 'y' using the size attribute. In this case, the size is 0 since 'y' is an empty array.


For more Practice: Solve these Related Problems:

  • Write a NumPy program to determine if an array is empty by checking its size attribute.
  • Create a function that returns a boolean indicating whether an array is empty, and test it on various shapes.
  • Test the emptiness check on arrays produced by slicing operations that may result in empty outputs.
  • Compare an empty array with a non-empty one by asserting that np.size returns 0 for the empty case.

Go to:


PREV : Frequency of Distinct Values in Array
NEXT : Divide Each Row by Vector


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.