Checking if a list is empty is one of the most common tasks in Python. Whether you’re handling API responses, validating user input, processing data, or writing automation scripts, you’ll encounter this check often. If you’re new to Python lists or Python data types, it’s a good idea to review them first.
- All Methods to Check If a List Is Empty in Python
- Method 1: if not my_list – The Best and Most Pythonic Way
- Method 2: len(my_list) == 0 – Explicit and Clear
- Method 3: not bool(my_list) – Verbose Alternative
- Method 4: my_list == [] (Works But Check First)
- Method 5: Index Access with Exception (Read Before Try)
- Performance Comparison (Python 3.12 Benchmarks)
- Common Pitfalls and How to Avoid Them
- Pitfall 1: Lists can contain “falsy” values but are not empty
- Pitfall 2: Handling None vs an empty list
- Pitfall 3: Mutable default arguments
- Real-World Use Cases
- Final Thoughts on Checking if a List Is Empty in Python
This guide explains all the common methods, when to use each, performance considerations, and common pitfalls to avoid. By the end, you’ll know the Pythonic way to check if a list is empty and how to write clean, professional code.
All Methods to Check If a List Is Empty in Python
Python provides several ways to check if a list is empty. Let’s go through them and discuss when to use each.
Method 1: if not my_list – The Best and Most Pythonic Way
This is the #1 recommended method by the Python community, Stack Overflow, and official documentation.
my_list = []
if not my_list:
print("List is empty") # → List is empty
my_list = [1, 2, "test"]
if not my_list:
print("Empty")
else:
print("Has items") # → Has itemsWhy it’s the best:
- Cleanest and most readable
- Fastest (direct internal size check)
- Works for all containers (dict, set, tuple, string)
- Recommended in 99% of cases
Method 2: len(my_list) == 0 – Explicit and Clear
This method is straightforward and can be helpful for beginners or teams that prefer explicit code.
my_list = []
if len(my_list) == 0:
print("List is empty") # → List is empty
my_list = ["a", "b", "c"]
if len(my_list) == 0:
print("Empty")
else:
print(f"Has {len(my_list)} items") # → Has 3 itemsWhen to choose this:
- Teaching beginners
- You need the length value anyway
- Working in a team that prefers explicit code
Method 3: not bool(my_list) – Verbose Alternative
This works the same as Method 1 but is longer and rarely used in practice.
my_list = []
if not bool(my_list):
print("List is empty") # → List is emptyRarely used in real code – stick to Method 1.
Method 4: my_list == [] (Works But Check First)
Technically correct but creates an unnecessary empty list object.
my_list = []
if my_list == []:
print("List is empty") # → List is emptyAvoid this – it’s slower and less Pythonic.
- Slower than Method 1
- Creates an unnecessary empty list object
- Less Pythonic
Method 5: Index Access with Exception (Read Before Try)
try:
my_list = []
my_list[0]
except IndexError:
print("List is empty")Using exceptions to check if a list is empty is not recommended. They are slower and make more sense for handling unexpected situations, not normal flow control. Learn more about Python exceptions and error handling.
Performance Comparison (Python 3.12 Benchmarks)
Testing different methods for checking if a list is empty is easy in Python. You can do this using the timeit module. Here’s an example setup that you can replicate yourself:
import timeit
my_list = []
# Define the different methods
methods = {
"if not my_list": "if not my_list: pass",
"len(my_list) == 0": "len(my_list) == 0",
"not bool(my_list)": "not bool(my_list)",
"my_list == []": "my_list == []"
}
# Measure time for each method with 100,000 repetitions
# number=100_000 means run 100000 times
results = {}
for name, code in methods.items():
results[name] = timeit.timeit(code, globals=globals(), number=100_000)
# Print results as a clean table
print("Method | Time (s)")
print("----------------------|----------")
for name, t in results.items():
print(f"{name:<21} | {t:.6f}")Example Output You Might See:
| Method | Time (s) |
|---|---|
| if not my_list | 0.0152 |
| len(my_list) == 0 | 0.0198 |
| not bool(my_list) | 0.0175 |
| my_list == [] | 0.0204 |
Tips for readers:
- You can change
number=100_000to a smaller value like10_000if you want faster results. - You can also test with larger lists or different contents to see how timings change.
- The key takeaway is that using
if not my_listis usually the fastest and cleanest approach. - For everyday code, any of the first three methods will work well. It is best to avoid
my_list == []because it is slower and less Pythonic.
Common Pitfalls and How to Avoid Them
When checking if a list is empty, it’s easy to make mistakes that can lead to bugs or unexpected behaviour. Here are some common mistakes and how to avoid them.
Pitfall 1: Lists can contain “falsy” values but are not empty
In Python, values like 0, False, "" (empty string), or None are considered “falsy”, they act like False in conditions. But a list containing these values is not empty, because it still has items.
my_list = [0, False, "", None] # 4 items
if not my_list:
print("This won't print")
print(len(my_list)) # → 4Pitfall 2: Handling None vs an empty list
Sometimes an API or function may return None instead of an empty list. It is important to check for None first before checking if the list is empty.
data = None # API might return None on error
if data is None:
print("No response")
elif not data:
print("Empty results")
else:
print("Got data")Pitfall 3: Mutable default arguments
Using mutable objects like lists as default arguments can lead to unexpected results because the same list is shared across function calls.
# BAD
def add_item(val, items=[]):
items.append(val)
return items
# GOOD
def add_item(val, items=None):
if items is None:
items = []
items.append(val)
return itemsReal-World Use Cases
Here are some practical examples where checking if a list is empty is useful:
results = [] # API result example
selected_items = [] # Form example
batches = [[], [1,2]] # Data pipeline
errors = [] # Testing
# API handling (safe)
message = {"message": "No data found"} if not results else {"data": results}
# Form validation (safe)
def show_error(): print("Error: No items selected")
if not selected_items: show_error()
# Data pipelines (safe)
for batch in batches:
if not batch: continue
print("Processing batch:", batch)
# Testing (safe)
if not errors: print("All tests passed")Final Thoughts on Checking if a List Is Empty in Python
Checking if a list is empty is one of those small but very common tasks in Python. By understanding the different methods, their performance, and common pitfalls, you can write code that is both clean and Pythonic.
The simplest and most reliable way to check if a list is empty is:
my_list = []
if not my_list:
print("Do something...")This method is concise, readable, and works for all standard Python containers. Use len(my_list) == 0 only if you specifically need the length value or want extra clarity.
By adopting this approach, you can avoid subtle bugs, improve code readability, and make your Python code more professional.
Happy coding!
