Check if a List is Empty in Python
To check if a list is empty in Python, you can use the if not list condition, the len() function, or compare it with an empty list []. Each approach ensures an efficient way to determine whether a list has elements or not.
Examples
1. Check if a List is Empty using if not list (Pythonic Way)
Python considers an empty list as False when used in a boolean context. This allows us to check if a list is empty using if not.
# Creating an empty list
my_list = []
# Checking if the list is empty
if not my_list:
print("The list is empty.")
else:
print("The list is not empty.")
Explanation:
Here, my_list is initialized as an empty list. The statement if not my_list evaluates to True because the list contains no elements, triggering the first print() statement.
Output:
The list is empty.
2. Check if a List is Empty using len() Function
The len() function returns the number of elements in a list. If it returns 0, the list is empty.
# Creating an empty list
my_list = []
# Checking if the list is empty using len()
if len(my_list) == 0:
print("The list is empty.")
else:
print("The list is not empty.")
Explanation:
Here, len(my_list) calculates the number of elements in the list. Since len(my_list) is 0, the condition len(my_list) == 0 evaluates to True, and it prints “The list is empty.”
Output:
The list is empty.
3. Comparing with an Empty List []
We can compare the list directly with an empty list [] to check if it is empty.
# Creating an empty list
my_list = []
# Checking if the list is empty by comparing with []
if my_list == []:
print("The list is empty.")
else:
print("The list is not empty.")
Explanation:
Here, we use the equality operator == to check if my_list is equal to an empty list []. Since both are empty, the condition evaluates to True and prints “The list is empty.”
Output:
The list is empty.
4. Check if a List is Empty using bool() Function
The bool() function converts a list into a boolean value, returning False if it is empty and True otherwise.
# Creating an empty list
my_list = []
# Checking if the list is empty using bool()
if not bool(my_list):
print("The list is empty.")
else:
print("The list is not empty.")
Explanation:
The bool(my_list) function returns False for an empty list. Using if not bool(my_list), we check if the list is empty and print the appropriate message.
Output:
The list is empty.
Conclusion
Here are four effective ways to check if a list is empty in Python:
if not list: The most Pythonic way, as empty lists evaluate toFalse.len(list) == 0: Explicitly checks the length of the list.list == []: Directly compares the list with an empty list.bool(list): Converts the list into a boolean value.
Using if not list is the recommended approach for readability and efficiency in Python.
