Skip to main content

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:

  1. First, create a list that you want to check for emptiness. For example, let's create an empty list called my_list:
my_list = []
  1. To check if the list is empty, you can use the len() function. The len() 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."

  1. Alternatively, you can use the not keyword to check if a list is empty. When used with not, an empty list will evaluate to True, while a non-empty list will evaluate to False. 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."

  1. 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."

  1. If you want to check if a list is not empty, you can use the not keyword with len() 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.