How do I check if a list is empty in Python?
Short answer
Write if not items:. Empty collections are falsy in Python, so this reads better and works identically for lists, dicts, sets, tuples and strings.
items = []
if not items:
print("nothing here")#What is falsy in Python
False,None0,0.0,0j"",[],(),{},set(),range(0)
Everything else is truthy. That includes "0", "False" and [0] — all non-empty, therefore true.
#The alternatives
if len(items) == 0: # works, but wordier
if items == []: # works, but only for lists
if not items: # idiomaticThe idiomatic form is what other Python developers expect, and it works unchanged if items later becomes a set or a tuple.
#Checking for a non-empty list
if items:
print(f"{len(items)} items")#NumPy is the exception
NumPy arrays raise ValueError on truth testing, because the answer is ambiguous for more than one element. Use array.size == 0 there.