This tutorial will demonstrate how to check if a list is empty in Python. Essentially, we will check if the length of a list is 0.
Using the len()
function
The most straightforward way to achieve this is by using the len() function. If the length returned is 0 then the list is empty.
See the code below.
# Check if a list is empty in Python
empty_list = []
# Use len function to check if list is empty
if len(empty_list) == 0:
print("Empty List")
else:
print("List is not Empty")
# Output: Empty List
In the above example, we check if the list has 0 elements to determine whether it is empty.
Using the not
operator
Another way to check if a list is empty in Python is by using the not boolean operator in Python.
This operator returns True if the resultant expression is False. We can use the if not
expression, in this case, to check if a list is empty in Python.
See the code below.
# Check if a list is empty in Python
empty_list = []
# Use not operator to check if list is empty
if not empty_list:
print("Empty List")
else:
print("List is not Empty")
# Output: Empty List
To Conclude.
In this tutorial, we discussed several methods to check if a list is empty in Python. In the first method, we use the len()
function that returns the length of the list. In the second method, we use the if not
expression.
Fun Fact: Did you know you could create a list of zeros in Python? Learn more here.
Explore more from this category at Python Lists. Alternatively, search and view other topics at All Tutorials.