0
0
NumpyHow-ToBeginner ยท 3 min read

How to Check if a NumPy Array is Empty

To check if a NumPy array is empty, use the array.size attribute. If array.size equals 0, the array has no elements and is empty.
๐Ÿ“

Syntax

Use the size attribute of a NumPy array to find the total number of elements it contains.

  • array.size: Returns the number of elements in the array.
  • If array.size == 0, the array is empty.
python
import numpy as np

array = np.array([])

if array.size == 0:
    print("Array is empty")
else:
    print("Array is not empty")
Output
Array is empty
๐Ÿ’ป

Example

This example shows how to create an empty and a non-empty NumPy array, then check if each is empty using the size attribute.

python
import numpy as np

empty_array = np.array([])
non_empty_array = np.array([1, 2, 3])

print(f"empty_array.size = {empty_array.size}")
print(f"non_empty_array.size = {non_empty_array.size}")

if empty_array.size == 0:
    print("empty_array is empty")
else:
    print("empty_array is not empty")

if non_empty_array.size == 0:
    print("non_empty_array is empty")
else:
    print("non_empty_array is not empty")
Output
empty_array.size = 0 non_empty_array.size = 3 empty_array is empty non_empty_array is not empty
โš ๏ธ

Common Pitfalls

A common mistake is to check if the array itself is None or use if array: which does not work for NumPy arrays and raises an error. Always use array.size == 0 to check emptiness.

python
import numpy as np

array = np.array([])

# Wrong way - raises ValueError
# if array:
#     print("Array is not empty")

# Correct way
if array.size == 0:
    print("Array is empty")
else:
    print("Array is not empty")
Output
Array is empty
๐Ÿ“Š

Quick Reference

CheckCodeMeaning
Is array empty?array.size == 0True if no elements in array
Is array not empty?array.size > 0True if array has elements
โœ…

Key Takeaways

Use array.size to check the number of elements in a NumPy array.
An array is empty if array.size == 0.
Do not use if array: to check emptiness; it raises an error.
Checking array is None does not tell if the array is empty.
This method works for arrays of any shape or dimension.