How do I check if a list is empty?
What’s the quickest and most reliable way to determine whether a list has any elements or not? In this guide, we’ll explore simple methods to check for an empty list in Python and explain how they work behind the scenes.
To check if a list is empty in Python, there are a couple of easy and Pythonic ways to do it. Whether you’re validating input, controlling flow, or cleaning up data, knowing how to handle empty lists is a must.
The most common way:
my_list = []
if not my_list:
print("The list is empty")
- Python treats empty sequences (like lists, tuples, strings) as False in a boolean context.
- So not my_list will return True if the list is empty.
Other ways (less common but still valid):
Using len() function:
if len(my_list) == 0:
print("The list is empty")
- This works perfectly fine, though slightly more verbose than the previous method.
Checking against an empty list directly:
if my_list == []:
print("Empty list")
- Works, but not recommended as it’s less readable and not as flexible.
When to be cautious:
- Make sure your variable is indeed a list and not None, or you might get unexpected errors.
- If you’re working with a nested list or a list with falsey values (0, False, ''), checking emptiness like this still works fine.