Check whether a Python list is empty
Use a list’s truth value to test for emptiness, distinguish an empty list from None, and handle NumPy arrays separately.
For a value known to be a list, use if not items:. An empty list is false in a Boolean context; a nonempty list is true, regardless of whether its elements are themselves false.
items = []
if not items:
print('The list is empty')
assert bool([0]) is True
assert bool([False]) is True
Compare the common forms
if not items:
print('Empty')
if len(items) == 0:
print('Empty')
if items == []:
print('Empty')
All three work for an ordinary list. The first is the usual idiom; the second states a length condition explicitly. Comparing with [] adds an unnecessary empty-list comparison when you only need truth testing. Choose based on clarity rather than assuming the difference will materially affect performance.
Keep None separate when it has a different meaning
def process(items=None):
if items is None:
items = [] # No collection was supplied
if not items:
return 'No data'
return f'Processing {len(items)} items'
None and [] are both false, but an omitted argument and a supplied empty collection can have different meanings in your API. Check is None first if that distinction matters. This pattern also avoids a mutable list as a default argument.
Other false values
Empty strings, dictionaries, and sets, along with numeric zero, are also false. A truth test does not prove that the value is a list. If a function accepts mixed types, validate or narrow the type before applying list-specific behavior.
FAQ
Can I use the same test for a NumPy array?
Use array.size == 0 to test emptiness. Array truth conversion depends on its size and version and can raise an ambiguity error; it is not a reliable emptiness test. array.any() asks whether any elements are true, which is a different question.
Why prefer not items over items == []?
It states the intended emptiness check directly and works with other ordinary containers. The equality form is valid for lists; it is simply unnecessary for this purpose.
Contact us
Join the community
to join the community
Try Guance
Start online and pay only for what you use.
Get startedChoose a Guance plan