How to check if a list is empty in Python
How to check if a list is empty in Python.
Here's a step-by-step tutorial on how to check if a list is empty in Python:
- First, create a list that you want to check for emptiness. For example, let's create an empty list called
my_list
:
my_list = []
- To check if the list is empty, you can use the
len()
function. Thelen()
function returns the number of elements in a list. If the length of the list is 0, it means the list is empty. Here's an example:
if len(my_list) == 0:
print("The list is empty.")
In this example, if the length of my_list
is 0, it will print "The list is empty."
- Alternatively, you can use the
not
keyword to check if a list is empty. When used withnot
, an empty list will evaluate toTrue
, while a non-empty list will evaluate toFalse
. Here's an example:
if not my_list:
print("The list is empty.")
In this example, if my_list
is empty, it will print "The list is empty."
- Another way to check if a list is empty is by comparing it to an empty list using the equality operator
==
. If the two lists are equal, it means the list is empty. Here's an example:
if my_list == []:
print("The list is empty.")
In this example, if my_list
is equal to an empty list, it will print "The list is empty."
- If you want to check if a list is not empty, you can use the
not
keyword withlen()
function or compare it to an empty list using the inequality operator!=
. Here are the examples:
if len(my_list) != 0:
print("The list is not empty.")
or
if my_list != []:
print("The list is not empty.")
In both cases, if my_list
is not empty, it will print "The list is not empty."
That's it! You now know how to check if a list is empty in Python using multiple methods. Feel free to choose the method that suits your needs best in different situations.