We can easily check if a list is empty in Python. An empty list has length 0, and is equal to False, so to check if a list is empty, we can just check one of these conditions.
empty_list = []
#length check
if len(empty_list) == 0:
print("List is empty!")
#if statement check
if empty_list:
print("List is empty!")
#comparing to empty list
if empty_list == []:
print("List is empty!")
In Python, lists are a collection of objects which are unordered. When working with lists, it can be useful to be able to easily determine if the list is empty.
There are a few ways you can determine if a list is empty.
Of course, you can always test to see if the list is equal to another empty list. Second, the length of an empty list is 0. Finally, when converting an empty list to a boolean value, we get False.
In this case, we can use any one of these conditions to determine if a list is empty or not.
In the following Python code, you can see the three ways you ca check if a list is empty or not.
empty_list = []
#length check
if len(empty_list) == 0:
print("List is empty!")
#if statement check
if empty_list:
print("List is empty!")
#comparing to empty list
if empty_list == []:
print("List is empty!")
Checking if List is Empty with if Statement in Python
One fact we can use in Python to check if a list is empty is that a list that is empty is equivalent to the boolean value False.
In this case, we can test if a list is empty using a simple if statement.
empty_list = []
#if statement check
if empty_list:
print("List is empty!")
Checking if List is Empty Using Python len() Function
One of the ways we can easily check if a list is empty in Python is with the Python len() function.
The length of a list which is empty is 0.
Checking to see if a list is empty using the Python len() function is shown in the following Python code.
empty_list = []
if len(empty_list) == 0:
print("List is empty!")
Checking if List is Empty By Comparing to Another Empty List in Python
You can also check if a list is empty by comparing it to another empty list. This is the most obvious method and works if you want to check if a tuple is empty, or check if a set is empty.
Below is how to compare an empty list to another list to determine if the other list is empty or not.
empty_list = []
if empty_list == []:
print("List is empty!")
Hopefully this article has been useful for you to learn how to check if a list is empty in Python.