How to Check if a List is Empty in Python: Simple Guide
To check if a list is empty in Python, use the condition
if not my_list: which returns True if the list has no items. Alternatively, you can check the length with if len(my_list) == 0:.Syntax
There are two common ways to check if a list is empty in Python:
if not my_list:- This checks if the list is empty by evaluating its truthiness.if len(my_list) == 0:- This explicitly checks if the list length is zero.
Both methods return True when the list has no elements.
python
if not my_list: print("List is empty") if len(my_list) == 0: print("List is empty")
Example
This example shows how to check if a list is empty using both methods and prints a message accordingly.
python
my_list = [] if not my_list: print("The list is empty using 'if not my_list'") if len(my_list) == 0: print("The list is empty using 'len(my_list) == 0'")
Output
The list is empty using 'if not my_list'
The list is empty using 'len(my_list) == 0'
Common Pitfalls
Some beginners try to compare the list directly to an empty list like if my_list == []:. While this works, it is less efficient and less Pythonic than using if not my_list:. Also, avoid checking if my_list is None: because an empty list is not None.
python
my_list = [] # Less efficient way if my_list == []: print("List is empty (less efficient way)") # Recommended way if not my_list: print("List is empty (recommended way)")
Output
List is empty (less efficient way)
List is empty (recommended way)
Quick Reference
| Method | Description | Example |
|---|---|---|
| Using truthiness | Checks if list is empty by evaluating its truth value | if not my_list: |
| Using length | Checks if list length is zero | if len(my_list) == 0: |
| Comparing to empty list | Directly compares list to [] (less efficient) | if my_list == []: |
Key Takeaways
Use 'if not my_list:' to check if a list is empty in the most Pythonic way.
Checking 'len(my_list) == 0' also works but is more verbose.
Avoid comparing the list directly to [] for efficiency and style reasons.
An empty list is not the same as None; do not confuse these checks.