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.
In short, the best way to check if a list is empty is to take advantage of that list’s type flexibility. For example, the statement
if my_list will return true if the list is not empty. Of course, there are other ways to check if a list is empty like verifying its length and comparing it directly to another empty list.
If that’s all you needed, help grow the site by visiting my list of ways to support The Renegade Coder. Otherwise, drop down below for more details which include a video summary, several solutions with details, performance metrics, and even a social media challenge (see #RenegadePython on Twitter).
Table of Contents
If reading isn’t your thing, you can check out this YouTube video which covers mostly the same content. Honestly, you can probably read this article faster, but I appreciate the views!
If you decide to check out the video, I recommend hopping over to YouTube where you can access the timestamps for each solution. While you’re there, why not toss the video a like?
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.
Before we talk about that, I want to preface with a quick warning. In this article, we’re talking about native Python lists—not
numpy lists (as the following commenter learned the hard way).
At any rate, 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 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.
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
In this example, we create a list called
my_list which is empty. Then, we run the
len() method on it which should return zero. If all goes well, we’ll compare zero with zero to prove that the list empty.
If we were to run this solution on a few cases, we’d find that it actually works great:
>>> my_list = list() >>> if len(my_list) == 0: print("The list is empty") else: print("The list is not empty") "The list is empty" >>> my_list = ["red", "yellow", "green"] >>> if len(my_list) == 0: print("The list is empty") else: print("The list is not empty") "The list is not empty" >>> my_list = () >>> if len(my_list) == 0: print("The list is empty") else: print("The list is not empty") "The list is empty"
Unfortunately, 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 on dev.to, is to compare a list directly to an empty list:
my_list = list() if my_list == : pass # the list is empty
Once again, we create an empty list. Then, we compare that list directly to an empty list using the
== operator. If all goes well, we’ll be able to prove that
my_list is empty.
If we were to try this solution with a few inputs, we’d find that it works great for some inputs but not others:
>>> my_list = list() >>> if my_list == : print("The list is empty") else: print("The list is not empty") "The list is empty" >>> my_list = [1, 2, 3] >>> if my_list == : print("The list is empty") else: print("The list is not empty") "The list is not empty" >>> my_list = () >>> if my_list == : print("The list is empty") else: print("The list is not empty") "The list is not empty" # Uh oh!
Clearly, this solution works alright, but it’s not considered pythonic. After all, Python has two different types of list-like collections: tuples and lists. Tuples are immutable lists, and comparing an empty tuple to an empty list,
() == , would return false.
In other words, if you don’t know what type of collection you’re dealing with, this is not a good solution. Instead, you should leverage the following type flexibility solution.
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 according to the PEP 8 standard.
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
In this example, we create an empty list. Then, we check if the list is empty by checking if it’s not a populated sequence. As a result, we can pass any sequence here—not just lists—and get the result we expect.
Now, this may not seem very intuitive, but it is a part of 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.
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. If you want to learn more about performance testing in Python, check out my article titled How to Performance Test Python Code.
Like most of the articles in this series, I thought it would be fun to take what we learned a step further. In other words, now that we know how to check if a list is empty, let’s try to stretch our knowledge a bit.
Our challenge today takes this idea of “emptiness” a bit further. In particular, let’s try applying it to a different data structure: the dictionary. How can we write a program which detects if a dictionary is empty?
Try writing a bit of code that behaves something like the following pseudocode:
emptiness_detection(my_dict) # true iff empty
As always, if you come up with a solution, feel free to share it on Twitter using the hashtag #RenegadePython. If I see it, I’ll give it a share!
In the meantime, here’s my solution:
Apparently, type flexibility still works! I wonder if there are any other ways to solve this problem.
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, you might get some value out of my list of Python Code Snippets for Everyday Problems.
Otherwise, 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:
- Rock Paper Scissors Using Modular Arithmetic
- How to Write a List Comprehension in Python
- How to Check if a File Exists in Python
In addition, check out some of these Python books on Amazon (ad):
- Effective Python: 90 Specific Ways to Write Better Python
- Python Tricks: A Buffet of Awesome Python Features
- Python Programming: An Introduction to Computer Science
Thanks again for your support!