How to Check If a List is Empty in Python
To check if a list is empty in Python, you can use the len() function, an if statement, or the not operator with the bool() function.
The following examples show how to check if a list is empty in Python.
Using len() Function
We can use the len() function to check if a list is empty.
Suppose we have the following list:
# Declare list
list1 = []
# Check if the list is empty
if len(list1) == 0:
print("The list is empty.")
Output: 👇️
The list is empty.
In this example, we use the len() function to check if the length of list1 is 0, indicating that the list is empty.
Using if Statement
We can use an if statement to check if a list is empty.
Suppose we have the following list:
# Declare list
list1 = []
# Check if the list is empty
if not list1:
print("The list is empty.")
Output: 👇️
The list is empty.
In this example, we use an if statement to check if list1 is empty. The condition if not list1 evaluates to True if the list is empty.
Using not Operator & bool() Function
We can use the not operator with the bool() function to check if a list is empty.
Suppose we have the following list:
# Declare list
list1 = []
# Check if the list is empty
if not bool(list1):
print("The list is empty.")
Output: 👇️
The list is empty.
In this example, we use the not operator with the bool() function to check if list1 is empty. The condition if not bool(list1) evaluates to True if the list is empty.
Conclusion
We can use the len() function, an if statement, and the not operator with the bool() function to check if a list is empty in Python.