In this post, we will learn how to check if a list is empty in Python with detailed explanation and example.

Checking whether a list is empty or not is a common task when we work with real-life projects or dealing with any problem statement.

You can also check out our previous article đŸ‘‰Solution of Two Sum Problem in Python

Today I will teach you four different ways to check if a list is empty or not in Python. So let’s start learning.

Using If-Else Statements

Before jumping into the code, let’s first understand how an empty list evaluates in a boolean expression. As we all know, an if statement only executes if the expression is True. Therefore, if a list is empty, it is considered a falsy expression. This is why using an if-else statement allows us to easily determine if the list is empty or not. Let’s see how.

my_list = [1,2,3,4,5]

if my_list:
    print("List is not empty")
else:
    print("List is empty")

Output:

List is not empty

Using not Operator

The same above program is also rewritten using not operator. let’s see how

my_list = [1,2,3,4,5]

if not my_list:
    print("List is empty")
else:
    print("List is not empty")

Output:

List is not empty

Using len() Function

We also use the len() function to check if the list is empty or not. Basically, if the length of the list is equal to zero that means it is empty otherwise it is not empty.

my_list = []

if  len(my_list) == 0:
    print("List is empty")
else:
    print("List is not empty")

Output:

List is empty

Using == operator

We can also use the == operator to check if a list is empty by comparing the given list to an empty list. Let’s see how.

my_list = [1,2,3,4,5]

if my_list == []:
    print("List is empty")
else:
    print("List is not empty")

Output:

List is not empty
Author

Hi, I'm Yagyavendra Tiwari, a computer engineer with a strong passion for programming. I'm excited to share my programming knowledge with everyone here and help educate others in this field.

Write A Comment