Check if a list is empty or not in Python
In article we will explore the different ways to check if a list is empty with simple examples. The simplest way to check if a list is empty is by using Python's not operator.
Using not operator
The not operator is the simplest way to see if a list is empty. It returns True if the list is empty and False if it has any items.
a = []
if not a:
print("The list is empty")
else:
print("The list is not empty")
Output
The list is empty
Explanation:
- not a returns True because the list is empty.
- If there were items in the list, not a would be False.
Table of Content
Using len()
We can also use len() function to see if a list is empty by checking if its length is zero.
a = []
if len(a) == 0:
print("The list is empty")
else:
print("The list is not empty")
Output
The list is empty
Explanation: len(a) returns 0 for an empty list.
Using Boolean Evaluation Directly
Lists can be directly evaluated in conditions. Python considers an empty list as False.
a = []
if a:
print("The list is not empty")
else:
print("The list is empty")
Output
The list is empty
Explanation: An empty list evaluates as False in the if condition, so it prints "The list is empty".