How to Check If an Array is Empty in Python
To check if an array is empty in Python, you can use the size attribute or the shape attribute from the NumPy library.
The following examples show how to check if an array is empty in Python.
Using size Attribute
We can use the size attribute to check if an array is empty.
Suppose we have the following array:
# Import library
import numpy as np
# Declare array
num_array = np.array([])
# Check if the array is empty
if num_array.size == 0:
print("The NumPy array is empty.")
else:
print("The NumPy array is not empty.")
Output: 👇️
The NumPy array is empty.
In this example, we use the size attribute to check if the size of num_array is 0, indicating that the array is empty.
Using shape Attribute
We can use the shape attribute to check if an array is empty.
Suppose we have the following array:
# Import library
import numpy as np
# Declare array
num_array = np.array([25, 27, 39, 31])
# Check if the array is empty
if num_array.shape == (0,):
print("The NumPy array is empty.")
else:
print("The NumPy array is not empty.")
Output: 👇️
The NumPy array is not empty.
In this example, we use the shape attribute to check if the shape of num_array is (0,), indicating that the array is empty.
Conclusion
We can use the size and shape attributes from the NumPy library to check if an array is empty in Python.