Checking whether a Python array is empty is a common task when processing user input, reading files, analyzing data, or building algorithms. The simplest solution for a list is if not values: or if len(values) == 0:. NumPy arrays require a different approach, such as if arr.size == 0:, because Python does not allow an array with more than one element to be tested directly with if.
Introduction
Python programs frequently need to determine whether a collection contains any data. Developers commonly call these collections “arrays,” although Python has several distinct array-like types, including lists, NumPy arrays, array.array objects, tuples, and pandas Series.
The correct method depends on the object being checked. In real terms, a regular Python list can be tested with not values, but applying the same approach to a NumPy array can cause an error. Understanding these differences helps prevent confusing runtime exceptions and makes data-handling code more reliable.
The Simplest Way to Check an Empty Python List
For an ordinary Python list, use the not operator:
values = []
if not values:
print("The list is empty")
else:
print("The list contains data")
The expression not values evaluates to True when the list contains no elements. It is short, readable, and widely used in Python Less friction, more output..
The equivalent len() method is also clear:
values = [1, 2, 3]
if len(values) == 0:
print("The list is empty")
Both approaches work correctly:
empty_list = []
non_empty_list = [10, 20, 30]
print(not empty_list) # True
print(not non_empty_list) # False
Recommended List Checks
For normal lists, these options are valid:
if not values:— concise and Pythonicif len(values) == 0:— explicit and easy for beginnersif len(values) > 0:— useful when the positive condition is more natural
not values Versus values == []
Developers sometimes compare a list directly with an empty list:
values = []
if values == []:
print("The list is empty")
This works, but not values is generally preferred. It is more concise and works naturally with other empty sequences.
Direct equality can also be problematic for NumPy arrays. For example:
import numpy as np
values = np.array([])
if values == []:
print("The array is empty")
An empty NumPy array may return True in this particular case, but equality checks are not a reliable general method. Comparing a non-empty NumPy array with a Python list can produce unexpected results or raise a ValueError.
Use not values for lists and arr.size == 0 for NumPy arrays Worth keeping that in mind..
Checking an Empty NumPy Array
A NumPy array is different from a Python list. Because of that, it stores data in a contiguous numerical structure and supports multidimensional operations. Because of this, Python cannot automatically decide whether a NumPy array is “false” when it contains multiple values The details matter here. Took long enough..
This code raises an error:
import numpy as np
values = np.array([1, 2, 3])
if not values:
print("The array is empty")
The error occurs because NumPy arrays do not have a single meaningful truth value when they contain multiple elements Easy to understand, harder to ignore..
Instead, check the array’s size attribute:
import numpy as np
values = np.array([])
if values.size == 0:
print("The NumPy array is empty")
The size attribute represents the total number of elements in the array:
empty_array = np.array([])
numbers = np.array([1, 2, 3])
print(empty_array.size) # 0
print(numbers.size) # 3
print(empty_array.size == 0) # True
print(numbers.size == 0) # False
Checking the First Dimension
Sometimes you need to know whether the first dimension of a multidimensional array is empty:
import numpy as np
matrix = np.empty((0, 3))
if matrix.shape[0] == 0:
print("The first dimension is empty")
Here, matrix.shape is (0, 3). This means the array has zero rows and three columns The details matter here..
Use matrix.size == 0 when checking the total number of elements. Use matrix.shape[0] == 0 when checking whether the first axis has no entries It's one of those things that adds up..
Empty NumPy Arrays and NaN Values
An empty NumPy array contains no elements at all:
values = np.array([])
An array containing an empty string is not empty:
values = np.array([""])
An array containing NaN values is also not empty:
values = np.array([np.nan, np.nan])
These statements both return False:
print(values.size == 0)
print(len(values) == 0)
The array has elements, even if those elements are missing, invalid, or not meaningful.
If the goal is to check whether every element is NaN, use a separate condition:
import numpy as np
values = np.array([np.nan, np.nan])
if np.isnan(values).all():
print("Every element is NaN")
Do not confuse an empty array with an array whose contents are all missing values Practical, not theoretical..
Checking Other Empty Sequences
Although lists are the most common Python arrays, other collection types can also be empty Small thing, real impact..
Tuple
coordinates = ()
if not coordinates:
```python
coordinates = ()
if not coordinates:
print("The tuple is empty")
The not operator works here because tuples, like lists, implement the __len__ method and return False when they contain no items.
List
Lists follow the same pattern:
data = []
if not data:
print("The list is empty")
You can also use len(data) == 0, but the not form is more Pythonic and widely preferred Most people skip this — try not to..
Set
Sets behave identically:
unique_values = set()
if not unique_values:
print("The set is empty")
Dictionary
Dictionaries are also checked the same way:
config = {}
if not config:
print("The dictionary is empty")
String
Strings are a special case because they are sequences of characters:
text = ""
if not text:
print("The string is empty")
Be careful not to confuse an empty string with a string containing only whitespace:
text = " "
if not text.strip():
print("The string is empty or whitespace only")
Summary of Approaches
Different types require slightly different approaches:
| Type | Recommended Check |
|---|---|
| NumPy array | array.So naturally, size == 0 |
| NumPy array (first axis) | array. shape[0] == 0 |
| List, tuple, set, dict, str | not sequence |
| All sequences | len(sequence) == 0 |
| Array of all NaN | `np.isnan(array). |
The key takeaway is that NumPy arrays require explicit checks because they do not support Python's implicit boolean evaluation for multi-element arrays. For standard Python collections, the not operator remains the cleanest and most idiomatic solution.
Conclusion
Checking whether a collection is empty is a fundamental operation in Python programming, and the approach varies depending on the data structure involved. For standard Python sequences such as lists, tuples, sets, dictionaries, and strings, the not operator provides a concise and readable way to perform the check. Think about it: numPy arrays, however, require more explicit methods such as inspecting the size or shape attributes to avoid ambiguity and runtime errors. Day to day, understanding the distinction between an array that contains no elements and an array whose elements are invalid or missing—such as NaN values—is equally important for writing reliable data-handling code. By choosing the right method for each data type, developers can write clearer, more reliable programs that handle edge cases gracefully.