Here are four ways to check if a NumPy array is empty or not.
- Using np.any()
- Using np.size()
- Using size attribute
- Using shape attribute
Method 1: Using np.any()
The np.any() method is used to check whether any item in an array, along a given axis, evaluates to True. If it returns false then array is empty otherwise not.
Visual Representation
Example 1: One-dimensional array
import numpy as np
# Create an empty array
empty_array = np.array([])
print(empty_array)
is_empty_array = np.any(empty_array)
if is_empty_array == False:
print("Array is empty")
else:
print("Array is not empty")
Output
[]
Array is empty
Example 2: 2D (two-dimensional) array
import numpy as np
# Create a empty 2D array
empty_array = np.array([[], []])
print(empty_array)
is_empty_array = np.any(empty_array)
if is_empty_array == False:
print("2D Array is empty")
else:
print("2D Array is not empty")
Output
[]
2D Array is empty
Method 2: Using np.size()
The np.size() method returns the total number of elements in the given array. If the size is 0, the array is empty.
Visual Representation
Example
import numpy as np
empty_array = np.array([])
is_empty_array = np.size(empty_array)
print(np.size(empty_array))
if is_empty_array == 0:
print("Array is empty")
else:
print("Array is not empty")
Output
0
Array is empty
Method 3: Using size attribute
The .size attribute also returns the total number of elements in the array.
Visual Representation
Example
import numpy as np
empty_array = np.array([])
if empty_array.size == 0:
print("Array is empty")
else:
print("Array is not empty")
Output
Array is empty
Method 4: Using shape attribute
The .shape attribute returns a tuple representing the dimensions of the array. An empty array will have a shape with a dimension size of zero.
Visual Representation
Example
import numpy as np
empty_array = np.array([])
if empty_array.shape[0] == 0:
print("Array is empty")
else:
print("Array is not empty")
Output
Array is empty