e Learning

How to Check If List is Empty in Python

In this tutorial, you will learn how to check if a list is empty in the Python programming language.

check if list is empty python

There are a couple of ways we can do this. We can put the list we want to check into an if-else statement as shown in the following code example:

num_list = []

if num_list:
    print("The list is not empty")
else:
    print("The list empty")

When a list is used in an if statement, Python returns True if the list is not empty. If the list is empty, Python returns False.

The list is empty in this case, so the else statement will be executed.

The len() function returns the length of a list

We can also use the built-in len() function to check if a list is empty. If the list is empty, the len() function returns 0.

num_list = []

print(len(num_list))

Based on the len() function, we can write a custom function that checks if a list is empty, as shown in the following code example:

num_list = []

def is_empty(the_list):
    return len(the_list) == 0

print(is_empty(num_list))

In this example, the is_empty() function takes a list as an argument and returns True if the length of the list is 0. If the list contains at least one item, the is_empty() function will return False.