How To Check If a List Is Empty In Python?

Summary: One of the following methods can be used to check if a list is empty :-

  1. Boolean operator not
  2. Explicit check using len()
  3. Simple Work Around With []
  4. Using .size() with NumPy
  5. Using Exception Handling with iter() method

Problem: Given a list; how to check if it is empty?

Example: Consider the given list –

li = []
< Some Method To Check If List "li" Is Empty >

In this article let us quickly discuss the methods that can be used to check if a given list is empty. Without further delay let us dive into the solutions.

Method 1: Using Implicit Boolean Operator “not”

The easiest and the most pythonic solution to our problem statement is to use a Boolean operator to check if the list is empty. The table given below represents the Boolean operations available at our disposal in Python for operations like the ones we have in our case.

Now let us have a look at the following program –

li = []
if not li:
  print(li, " is empty")

Output:

[]  is empty

Method 2: Performing Explicit Check Using “len()”

You can also check if the list is empty or not explicitly using the len function.

  • len() is an inbuilt method in Python that returns the length of an object. It can be very useful for conditional checks or performing iterations through objects like strings, list, tuple, etc.

Let us have a look at the following program to understand how we can use the len() method to find the length of objects in Python and in the latter half of the program we will find out how we can leverage the len() method to find how to know if the list is empty or not.

name = "FINXTER"
d = {'name': 'FINXTER', 'founder': 'Christian Mayer'}
tup = {0,1,2,3,4}
li = []

# using len to fin out the length of the string name, tuple tup and dictionary d
print("Length of string name is ",len(name))
print("Length of tuple tup is ",len(tup))
print("Length of dictionary d is ",len(d))
print("Length of list li is ",len(li))

print("\n***Using len() to check if list li is empty***")

if len(li) == 0:
  print('The list li is Empty!')
else:
  print(li)

Output

Length of string name is  7
Length of tuple tup is  5
Length of dictionary d is  2
Length of list li is  0

***Using len() to check if list li is empty***
The list li is Empty!

From the above output it is evident that an empty list (or any other countable object) will have a length of zero.

Method 3: A Simple Work Around With []

Sometimes the easiest solutions are the ones that we don’t ponder upon thinking that they might not work. Here, let us discuss one such solution where you need not rack your brain to check if the list is empty. We can check if a given list is empty or not using the comparison operator == that compares two objects in Python.

Let us have a look at the code to find out if this works in our case –

li = []
if li == [] :
  print ("List 'li' is Empty!")

Output:

List 'li' is Empty!

Method 4: Using NumPy And .size

If you are using the NumPy library in your code then I am afraid the above proposed methods won’t work for you because:

1. If your array is not empty then NumPy casts the array to an array of bools. So using the conditional if x: will try to evaluate all of the bools at once to achieve an aggregate truth value. This doesn’t make sense, so you will get a ValueError. Also in case your array is empty, you will still get a similar warning as shown below:

2. The second problem is when you are using exactly one element in your NumPy array. In this case, the conditional if statement will work. However, if that one element in the array is 0 then though your program gets executed you won’t get the desired output because in this case, the if conditional check will result in False even though the array actually has an element in it i.e. 0.

3. The third issue is that when you use the inbuilt len() method you might get unexpected outputs. For example, if you are using a two-dimensional array then you might be having 6 elements in the array but the len() will only generate 2 based on the output based on the dimension of the array in use.

Let us have a look at the above discussed issues in a program given below :-

import numpy as np


#Reason 2: Array with 0 as single element
x = np.array([0,])
print("length of x is ",len(x))

# Reason 3: Unexpected results from len()
a = np.array([[1,2], [3,4]])
print("length of a is ",len(a))

# Reason 1: ValueError
li = np.array([0,1])

if not li:
 print(li)

Output:

length of x is  1
length of a is  2
Traceback (most recent call last):
  File "s1.py", line 15, in <module>
    if not li:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

This brings us to the question, What’s the NumPythonic Way?

The NumPythonic Way

The correct way of checking if the array is empty in case of using the NumPy library is given by using the size() function. This inbuilt function of the NumPy library counts the number of elements in a given array along a given axis. If the default axis is not specified, it will take all the available axis into consideration.

Let us have a look at the following program which uses the size function to overcome the shortcomings of the above methods :-

import numpy as np


#Reason 2: Array with 0 as single element
x = np.array([0,])
print("length of x is ",x.size)

# Reason 3: Solution to len()
a = np.array([[1,2], [3,4]])
print("length of a is ",a.size)

# Reason 1: Solution to ValueError
li = np.array([])

if not li.size:
 print(li, "is Empty!")

Output:

length of x is  1
length of a is  4
[] is Empty!

Method 5: Using Exception and iter()

This might be a silly approach but nevertheless, it works. So let us have a look at how we can use exception handling along with iter() method to solve our problem.

li = []
try:
  x = next(iter(li))
  print(x)
except StopIteration:
  print("li is empty")

Output:

li is empty

Note:- iter() is an inbuilt method in Python which creates an iterable object that can be iterated with one element at a time.

Conclusion

I hope the methods discussed in this article help you to detect the presence of elements in a list and use them accordingly in your code. Please subscribe and stay tuned for more interesting articles!

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!