numpy
python
array
check-array
programming-tips

How can I check whether a numpy array is empty or not?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

A NumPy array is "empty" when it has zero elements (size == 0). This can happen with explicit empty arrays (np.array([])), arrays with zero-length dimensions (np.empty((0, 3))), or as the result of filtering operations that match nothing. The recommended way to check is array.size == 0. Avoid using Python's len() or truthiness checks (if array:) because they behave differently for multi-dimensional arrays and NumPy intentionally raises an error for ambiguous boolean evaluation.

Checking with .size

python
1import numpy as np
2
3# Empty array
4arr = np.array([])
5print(arr.size)    # 0
6print(arr.size == 0)  # True
7
8# Non-empty array
9arr = np.array([1, 2, 3])
10print(arr.size)    # 3
11print(arr.size == 0)  # False
12
13# Multi-dimensional empty array
14arr = np.empty((0, 5))
15print(arr.shape)   # (0, 5)
16print(arr.size)    # 0 — zero elements even though shape has 2 dimensions
17print(arr.size == 0)  # True
18
19# Array with a single zero is NOT empty
20arr = np.array([0])
21print(arr.size)    # 1
22print(arr.size == 0)  # False — it has one element (the value 0)

Why Not Use len()?

python
1import numpy as np
2
3# len() returns the size of the first dimension, not total elements
4arr = np.empty((0, 3))
5print(len(arr))      # 0 — happens to work here
6
7arr = np.empty((3, 0))
8print(len(arr))      # 3 — WRONG! Array has 0 elements but len() says 3
9
10arr = np.array([1, 2, 3])
11print(len(arr))      # 3 — correct for 1D
12
13# 0-dimensional array
14arr = np.array(42)
15# len(arr) raises TypeError: len() of unsized object

len() measures the first axis only. For multi-dimensional arrays or scalar arrays, it gives misleading or broken results. Always use .size.

Why Not Use if array:?

python
1import numpy as np
2
3arr = np.array([1, 2, 3])
4
5# This raises an error in NumPy
6if arr:
7    print("not empty")
8# ValueError: The truth value of an array with more than one element is ambiguous.
9# Use a.any() or a.all()
10
11# Single-element array works but is misleading
12arr = np.array([0])
13if arr:
14    print("not empty")
15# Does NOT print — the single element is 0 (falsy), but the array is NOT empty

NumPy intentionally makes boolean evaluation ambiguous for multi-element arrays. Do not use if array: to check emptiness.

Checking After Filtering

python
1import numpy as np
2
3data = np.array([10, 20, 30, 40, 50])
4
5# Filter: values greater than 100
6result = data[data > 100]
7print(result)         # []
8print(result.size)    # 0
9
10if result.size == 0:
11    print("No values matched the filter")
12else:
13    print(f"Found {result.size} values: {result}")

Checking for None vs Empty

python
1import numpy as np
2
3def process_data(arr):
4    # Check for None first, then empty
5    if arr is None:
6        print("No array provided")
7        return
8
9    if arr.size == 0:
10        print("Array is empty")
11        return
12
13    print(f"Processing {arr.size} elements")
14
15process_data(None)            # No array provided
16process_data(np.array([]))    # Array is empty
17process_data(np.array([1]))   # Processing 1 elements

Creating and Working with Empty Arrays

python
1import numpy as np
2
3# Different ways to create empty arrays
4a = np.array([])              # 1D, float64, 0 elements
5b = np.empty((0,))            # 1D, float64, 0 elements
6c = np.empty((0, 3))          # 2D, 0 rows, 3 columns
7d = np.zeros((0, 4, 5))       # 3D, 0 elements
8
9# Empty arrays preserve dtype
10e = np.array([], dtype=np.int32)
11print(e.dtype)  # int32
12
13# Concatenating with empty arrays
14arr = np.array([])
15arr = np.append(arr, [1, 2, 3])
16print(arr)  # [1. 2. 3.]
17# Warning: np.append is slow in loops — use lists and convert at the end

Common Pitfalls

  • Using if not array for emptiness check: NumPy arrays do not support Python truthiness for arrays with more than one element. This raises ValueError. Always use array.size == 0 instead of boolean evaluation.
  • Confusing np.empty() with an empty array: np.empty((3, 3)) creates a 3x3 array with uninitialized (garbage) values — it is NOT empty. np.empty((0, 3)) creates an array with zero rows, which IS empty. The name empty refers to "uninitialized", not "zero elements".
  • Using len() on multi-dimensional arrays: len(np.empty((3, 0))) returns 3, but the array has zero elements. len() only measures the first dimension. Use .size which returns the total element count across all dimensions.
  • Treating an array of zeros as empty: np.zeros(5) has 5 elements that happen to be zero. It is NOT empty (size == 5). Emptiness means no elements at all, not elements with value zero.
  • Building arrays with np.append in a loop: Starting with np.array([]) and appending in a loop is extremely slow (O(n^2) total time) because NumPy copies the entire array on each append. Instead, collect values in a Python list and convert once: np.array(my_list).

Summary

  • Use array.size == 0 to check if a NumPy array is empty — this works for all dimensions
  • Do not use if array: — NumPy raises ValueError for multi-element arrays
  • Do not use len() — it only measures the first dimension, not total element count
  • Check is None separately before checking .size if the variable may not be a NumPy array
  • np.empty((n, m)) with any zero dimension creates a truly empty array; np.empty((n, m)) with all positive dimensions creates an uninitialized (non-empty) array

Course illustration
Course illustration

All Rights Reserved.