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
Why Not Use len()?
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:?
NumPy intentionally makes boolean evaluation ambiguous for multi-element arrays. Do not use if array: to check emptiness.
Checking After Filtering
Checking for None vs Empty
Creating and Working with Empty Arrays
Common Pitfalls
- Using
if not arrayfor emptiness check: NumPy arrays do not support Python truthiness for arrays with more than one element. This raisesValueError. Always usearray.size == 0instead 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 nameemptyrefers 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.sizewhich 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.appendin a loop: Starting withnp.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 == 0to check if a NumPy array is empty — this works for all dimensions - Do not use
if array:— NumPy raisesValueErrorfor multi-element arrays - Do not use
len()— it only measures the first dimension, not total element count - Check
is Noneseparately before checking.sizeif 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

