How to check if array is empty?

In this tutorial, we’ll explore how to check if an array is empty in the NumPy library using a clever trick. Verifying whether an array is empty is a common task in data manipulation and analysis, and NumPy provides an efficient way to do this.

Numpy check if array is empty

Checking if empty

To check if an array is empty it is enough to check the size of the array.

See also  How to create empty array in Numpy?

Let’s examine a function that determines and prints whether an array is empty.

import numpy as np

my_array = np.array([])

def if_empty_array(array):
    if array.size == 0:
        print(f"Array is empty")
        print(f"Array is NOT empty")


In this code, we define the if_empty_array function, which takes an array as its argument. Within the function, we use the size attribute of the array to check if it’s equal to zero. If the size is zero, we print “Array is empty”; otherwise, we print “Array is NOT empty”.

See also  How to trim an array with Numpy clip?

Running this code with an empty array results in the message “Array is empty”.

By using this clever trick, you can efficiently check if an array is empty, making it a valuable tool for array validation and data processing tasks in Python.