View

Check for empty lists in python

I use lists all the time in my code. Sometimes I have to check for empty lists in my python code.

Introduction

Lists are in every programming language a common data structure. In python lists are mutable and of course you can iterate over a list.

I do want to know in several situations if a list is empty. Python provides several ways to check if a list is empty or not. I will mention some ways to check for empty lists in python in this post.

The len() function

Python has a built in function len(). We can use this function th check if a list is empty.

my_list = []
if len(my_list):
    print('the list is not empty')
else:
    print('the list is empty')

This script prints the following:

List is empty

len(my_list) produces 0. The if function will cast it to a boolean value of False. In this case when the list is empty, the program will execute the else block.

The len() function (Second solution)

The following example is in fact the same as the previous example. We do not let python do the cast for us. We check if the length of the list is 0.

my_list = []
if len(my_list) == 0:
    print('the list is empty')
else:
    print('the list is not empty')

This code will check if the list has 0 items. You can also check for other values. For example we can check if a list contains 3 items.

Compare with the empty list

This method is also very simple. Just compare with an empty list.

my_list = []
if my_list == []:
    print('the list is empty')
else:
    print('the list is not empty')

Check the list itself

You can also just check the variable itself. In case the list is empty, the else block will be executed.

my_list = []
if my_list:
    print('the list is not empty')
else:
    print('the list is empty')

An empty list is an empty collection. This empty collection is converted automatically to a Boolean.

This is the preferred approach according to the python documentation. It is the cleanest and shortest solution.

Conclusion

This article talked about several ways to check for empty lists in python. The last example is the preferred way.

About the author

I currently work as a Test Automation Consultant at b.ignited. Here I work for different clients in different industries to help them start and speed up their testing cycles

I’ve been testing software since 2000 when I became involved in testing telephone applications and hardware. Since then, I’ve been able to expand my experience by testing a variety of embedded, web, mobile and desktop applications. I have used various development methodologies from waterfall to agile.

I consider myself to be a lifelong learner.