How to Check if a List is Empty in Python

How to Check if a List is Empty in Python Featured Image

Last Updated on

Once again, welcome back to another issue of the How to Python series. Today, we’re going to learn how to check if a list is empty in Python.

Table of Contents

Problem Introduction

So far, we’ve played a lot with data structures like lists and dictionaries. In terms of lists, we’ve learned how to sum elements of two lists, and we’ve even learned how to convert two lists into a dictionary. However, in all this list manipulation, we’ve never actually discussed how to check if a list is empty.

Detecting an empty list is an important skill to learn as a Python developer. It allows us to handle errors that can occur when attempting to manipulate an empty list. For example, we all know what happens when we try to index an empty list:

Python 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 17:26:49) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> my_list = list()
>>> my_list[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

If we happen to have a function that does some indexing, maybe it’s a good idea to add a protective check for an empty list. After all, handling edge cases is an important skill to learn for any coder.

Solutions

When it comes to checking if a list is empty in Python, there are a handful of solutions such as:

  • Verifying the list’s length is zero
  • Comparing the list directly to another empty list
  • Checking that the list is empty by its type flexibility (preferred method)

Be sure to weigh the pros and cons of each solution before making your decision.

Check if a List is Empty by its Length

Alright, so the first method for checking if a list is empty is to verify that the length of the list is zero. As someone who learned Java first, I find this solution very intuitive. Take a look:

my_list = list()
if len(my_list) == 0:
    pass  # the list is empty

The drawback of this method is that it isn’t very pythonic. After all, the Python community is very strict about its idioms, so it’s probably a good idea to avoid this method if possible.

Check if a List is Empty by Direct Comparison

Another solution, as mentioned by vorsprung, is to compare a list directly to an empty list:

my_list = list()
if my_list == []:
    pass  # the list is empty

This solution works just as well as the previous solution, but it’s also not considered pythonic. The reason being that Python has two different types of list-like collections: tuples and lists. Tuples are immutable lists, and comparing a empty tuple to an empty list, () == [], would return false.

Regardless, both solutions are valid. In the next section, we’ll cover the community accepted list emptiness test.

Check if a List is Empty by its Type Flexibility

Dynamic typing is a fun feature of Python because it allows a variable to assume many forms. While someone with a static typing background might find this frustrating, others will find that dynamic typing in Python has its perks. Among those perks is the fact that empty sequences evaluate to false.

So, what does that mean in terms of code? Well, it means we can treat a list like a boolean. For example:

my_list = list()
if not my_list:
    pass  # the list is empty

Now, this may not seem very intuitive, but it is the accepted PEP 8 standard. In other words, this is the method we should use in production code. Always check if a list is empty by its type flexibility.

Performance

In terms of performance, there is a clear winner. That said, to prove that, we’ll need to setup a few strings for testing:

setup = "my_list = list()"

length = """
if len(my_list) == 0:
    pass
"""

direct = """
if my_list == []:
    pass
"""

flex = """
if not my_list:
    pass
"""

With these strings, we’re able to leverage the timeit library as follows:

>>> import timeit
>>> min(timeit.repeat(stmt=length, setup=setup, repeat=10))
0.06464349999998831
>>> min(timeit.repeat(stmt=direct, setup=setup, repeat=10))
0.03562890000000607
>>> min(timeit.repeat(stmt=flex, setup=setup, repeat=10))
0.016961899999955676

Here, we’ve used the repeat function to run the test 10 times before pulling out a lower bound run time. In this case, the direct comparison method is about twice as fast as checking the length. That said, the type flexibility method is even faster still.

For the sake of completeness, we’ll need to run these tests on a list that isn’t empty. As a result, we’ll have to update the setup variable to something like the following:

setup = "my_list = [1, 5, 6, -4, 12, 3, 1, 1, 0]"

Then, if we rerun our tests, we can observe any changes in execution time:

>>> min(timeit.repeat(stmt=length, setup=setup, repeat=10))
0.06420660000003409
>>> min(timeit.repeat(stmt=direct, setup=setup, repeat=10))
0.03376020000007429
>>> min(timeit.repeat(stmt=flex, setup=setup, repeat=10))
0.012936999999965337

As it turns out, run times are about the same. In other words, the recommended type flexibility idiom performs the best in both cases. For reference, these tests were performed using Windows 10 and Python 3.7.3.

A Little Recap

Today’s topic is how to check if a list is empty in Python. As always, in this section, we do a little recap of the solutions we’ve shared above:

my_list = list()

# Check if a list is empty by its length
if len(my_list) == 0:
    pass  # the list is empty

# Check if a list is empty by direct comparison
if my_list == []:
    pass  # the list is empty

# Check if a list is empty by its type flexibility **preferred method**
if not my_list:
    pass  # the list is empty

And with that, we’re finished. Once again, thanks for stopping by. Hopefully, this was helpful! If so, consider subscribing to The Renegade Coder to get more content like this straight to your inbox—plus a handful of other benefits like access to the blog. If you just want the weekly newsletter, drop your email into the signup form.

In the meantime, check out some of these other awesome Python articles:

Of course, you can also support The Renegade Coder by making your way over to Amazon to pick up any of the following Python books:

Thanks again for your support!

Series Navigation← How to Convert Two Lists into a Dictionary in PythonHow to Clone a List in Python →
Advertisements

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.