Check if NumPy Array is Empty in Python

Recently, I was working on a data analysis project where I needed to verify if a NumPy array was empty before performing calculations. The issue is, there are multiple ways to check for empty arrays in NumPy, and choosing the right one can impact your code’s efficiency and readability.

In this article, I’ll cover seven practical methods you can use to check if a NumPy array is empty in Python (including size-based checks, logical functions, and comparison methods).

So let’s dive in!

Methods to Check if a NumPy Array is Empty in Python

Let me explain to you the important methods to check if a NumPy array is empty in Python.

Read Python NumPy Not Found: Fix Import Error

Method 1 – Use the size Attribute

The simplest way to check if a NumPy array in Python is empty is by using the size attribute. This returns the total number of elements in the array.

import numpy as np

# Create an empty array
empty_array = np.array([])

# Check if the array is empty
is_empty = empty_array.size == 0

print(f"Is the array empty? {is_empty}") 

Output:

Is the array empty? True

I executed the above example code and added the screenshot below.

check if numpy array is empty

This method is simple and intuitive – if the size is 0, then the array is empty. It works for arrays of any dimension.

Check out Create a Matrix in Python

Method 2 – Use the len() Function with size

Another approach combines Python’s built-in len() function with the array’s size attribute:

import numpy as np

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

# Check if arrays are empty
print(f"Empty array check: {len(empty_array.shape) > 0 and empty_array.size == 0}")
print(f"Non-empty array check: {len(non_empty_array.shape) > 0 and non_empty_array.size == 0}")

Output:

Empty array check: True
Non-empty array check: False

I executed the above example code and added the screenshot below.

check if NumPy array is empty python

This method is helpful when you want to ensure you’re dealing with at least a one-dimensional array.

Read Random Number Between Two Values in Numpy

Method 3 – Use the shape Attribute

The shape attribute provides the dimensions of the Python array. For an empty array, at least one dimension will have size 0:

import numpy as np

# Create different kinds of empty arrays
empty_1d = np.array([])
empty_2d = np.zeros((0, 3))
empty_3d = np.zeros((2, 0, 4))

# Check if arrays are empty
print(f"1D array: {0 in empty_1d.shape}")
print(f"2D array: {0 in empty_2d.shape}")
print(f"3D array: {0 in empty_3d.shape}") 

# Non-empty array for comparison
non_empty = np.array([[1, 2], [3, 4]])
print(f"Non-empty array: {0 in non_empty.shape}")

Output:

1D array: True
2D array: True
3D array: True
Non-empty array: False

I executed the above example code and added the screenshot below.

python check if NumPy array is empty

This method is particularly useful for multidimensional arrays where you need to check if any dimension is empty.

Check out Create a Python Empty Matrix

Method 4 – Use the any() or all() Functions

For more complex empty array checks, you can leverage NumPy’s logical functions:

import numpy as np

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

# Using any() to check if the array is empty
is_empty_any = not np.any(empty_array.shape)
print(f"Is empty (using any): {is_empty_any}")  # False - not reliable for 1D empty arrays!

# Using any() with 0 in shape (more reliable)
is_empty_better = 0 in empty_array.shape
print(f"Is empty (using 0 in shape): {is_empty_better}")  # True

# For multidimensional arrays
empty_2d = np.zeros((0, 5))
is_empty_2d = 0 in empty_2d.shape
print(f"Is 2D array empty: {is_empty_2d}")  # True

Be careful with the direct use of any() or all() as they can be tricky with one-dimensional arrays, checking for zero in the shape is more reliable.

Read NumPy Reset Index of an Array in Python

Method 5 – Comparison with np.array([])

You can also directly compare with an empty array:

import numpy as np

test_array = np.array([])
is_empty = np.array_equal(test_array, np.array([]))
print(f"Is the array empty? {is_empty}")  # True

This method is intuitive but slightly less efficient than checking the size attribute.

Method 6 – Use the ndim and size Properties Together

For more comprehensive checks, especially with multi-dimensional arrays:

import numpy as np

# Different types of arrays
empty_array = np.array([])
empty_2d = np.zeros((0, 3))
scalar = np.array(5)  # Scalar (0-dim array)
non_empty = np.array([1, 2, 3])

# Define a function to check if an array is empty
def is_empty_array(arr):
    return arr.size == 0

# Check various arrays
print(f"Empty 1D: {is_empty_array(empty_array)}")  # True
print(f"Empty 2D: {is_empty_array(empty_2d)}")     # True
print(f"Scalar: {is_empty_array(scalar)}")         # False
print(f"Non-empty: {is_empty_array(non_empty)}")   # False

This approach uses the size property, which works universally across different array dimensions.

Read np.genfromtxt() Function in Python

Method 7 – Use a Try-Except Block

If you’re concerned about handling edge cases, a try-except approach can be robust:

import numpy as np

def is_empty_safe(arr):
    try:
        # Try to access the first element
        first_element = arr.flat[0]
        return False  # If we get here, the array has at least one element
    except IndexError:
        return True  # An IndexError means the array is empty

# Test with different arrays
empty_array = np.array([])
non_empty = np.array([1, 2, 3])
empty_2d = np.zeros((0, 5))

print(f"Empty 1D: {is_empty_safe(empty_array)}")  # True
print(f"Non-empty: {is_empty_safe(non_empty)}")   # False
print(f"Empty 2D: {is_empty_safe(empty_2d)}")     # True

While this method works, it’s generally slower than directly checking the size attribute and should be used only when needing maximum robustness.

Check out np.savetxt() Function in Python

Real-World Application: Data Preprocessing

Let me share a real-world example where checking for empty arrays is crucial. Imagine we’re processing financial transaction data for a US-based retail company:

import numpy as np

def process_sales_data(daily_transactions):
    """Process daily sales transactions, skipping days with no data."""
    total_revenue = 0
    processed_days = 0

    for day, transactions in enumerate(daily_transactions, 1):
        # Skip processing if no transactions for the day
        if transactions.size == 0:
            print(f"Day {day}: No transactions recorded, skipping analysis")
            continue

        daily_revenue = np.sum(transactions)
        total_revenue += daily_revenue
        processed_days += 1
        print(f"Day {day}: ${daily_revenue:.2f} from {transactions.size} transactions")

    if processed_days > 0:
        average_daily_revenue = total_revenue / processed_days
        print(f"\nAverage daily revenue: ${average_daily_revenue:.2f}")
    else:
        print("\nNo data available for analysis")

# Sample data: 7 days of transactions (some days have no data)
weekly_data = [
    np.array([45.99, 23.50, 12.99, 78.25]),  # Monday
    np.array([]),                           # Tuesday (holiday - no transactions)
    np.array([34.78, 98.45, 23.45]),        # Wednesday
    np.array([56.78, 12.34, 98.76, 34.56]), # Thursday
    np.array([]),                           # Friday (system down - no data)
    np.array([87.65, 23.45, 65.43]),        # Saturday
    np.array([34.56, 78.90])                # Sunday
]

process_sales_data(weekly_data)

In this example, checking for empty arrays allows us to gracefully skip days with no transaction data while still calculating meaningful statistics for the business.

I hope you found this article helpful. Both methods work great – the size attribute check is quick and simple for most use cases, while the shape-based check is particularly useful for multidimensional arrays. Choose the method that best fits your specific needs.

Related tutorials you may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.