Python Check if List is Empty (in 5 Ways)


If you are a Python developer, you may need to check if a list is empty from time to time.

In Python, a list is a collection of items, and sometimes you need to know whether a list is empty or not before performing any operation on it.

In this article, we will discuss multiple ways to check if a list is empty in Python.

    Table of Contents

  1. Using len() function
  2. Using not operator
  3. Using bool() function
  4. Using == operator
  5. Using any() function
  6. Conclusion

1. Using len() function

The first and easiest way to check if a list is empty in Python is by using the len() function.

It returns the number of elements in a list. If the length of a list is 0, it means the list is empty.

Let's see an example:

Example
my_list = []

# check if list is empty
if len(my_list) == 0:
    print("The list is empty")
The list is empty

2. Using not operator

Another way to check if a list is empty in Python is by using the not operator.

The not operator returns the opposite of a Boolean value. So, if the list is empty, the not operator will return True.

Here is an example:

Example
my_list = []

# check if list is empty
if not my_list:
    print("The list is empty")
The list is empty

3. Using bool() function

The bool() function returns a Boolean value, True or False, based on the input it receives. When an empty list is passed as an argument to the bool() function, it returns False.

Here is an example to check if a list is empty using the bool() function:

Example
my_list = []

# check if list is empty
if bool(my_list) == False:
    print("The list is empty")
The list is empty

4. Using == operator

The == operator is used to compare two values. To check if a list is empty, we can compare it with an empty list.

For example, [] == [] will return True because both the lists are empty.

Example
my_list = []

# check if list is empty
if my_list == []:
    print("The list is empty")
The list is empty

5. Using any() function

The any() function takes an iterable as an argument and returns True if any of the elements in the iterable is True. Otherwise, it returns False.

If we pass an empty list to the any() function, it will return False.

Example
my_list = []

# check if list is empty
if not any(my_list):
    print("The list is empty")
The list is empty

Conclusion

There are multiple ways to check if a list is empty in Python. In this article, we have discussed 5 different ways for this.

Hope this was helpful.

Happy Learning!😇