How to Check if List is Empty in Python

Introduction

Lists are one of the four most commonly used data structures provided by Python. Its functionality, extensibility, and ease of use make it useful for implementing various types of functionalities.

Python lists have a few interesting characteristics:

  1. Mutability - meaning it can change, which means it allows us to easily add and delete entries from it. This is the main difference between Python lists and tuples
  2. Iterability - which means we can iterate through it (go through all elements in the list in-order)

The main attribute that will be focusing on is Iterability. An important part when dealing with an iterable object, in this case a list, is checking if there's anything to iterate through. If not handled properly, this can lead to a lot of unwanted errors.

Python provides various ways to check if our list is empty or not, some implicit and some explicit, and in this article, we'll go over how to check if a Python list is empty.

Using len() Function

One of the techniques is to use the len() function to check if our list is empty or not:

py_list = []

"""
Here len() returns 0, which is 
implicitly converted to false
"""

if len(py_list):
    print('The list is not empty')
else:
    print('T list is empty')

Output

List is empty

When len(py_list) executes it produces zero, which is then implicitly cast to the boolean value of False. Thus in case of an empty list the program will be redirected to the else block.

Although this method looks simple, it's not that intuitive for beginners.

Using len() With Comparison Operator

This technique is similar to the one above but it is more explicit and easy to understand. That's why those who are new to python or coding itself usually consider it more intuitive:

if len(py_list) == 0:
    print('List is empty')
else:
    print('List not empty')

In the code above, len(py_list) == 0 will be true if the list is empty and will will be redirected to the else block. This also allows you to set other values as well, rather than relying on 0 being converted as False. All other positive values are converted to True.

Comparison With Empty List

This method is also very simple and works well for beginners as it involves comparing with an empty list:

if py_list == []:
    print('List is empty')
else:
    print('List is not empty')

Here again, we are using the comparison operation to compare one list with another - an empty one, and if both are empty the if block will execute.

Pep-8 Recommended Style

#PEP-8 recommended style

if py_list:
    print('List is not empty')
if not py_list:
    print('List empty')

For this, let's take a look at Truth Value Testing. The official docs state that:

Here are most of the built-in objects considered false:

  • constants defined to be false: None and False.
  • zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)
  • empty sequences and collections: '', (), [], {}, set(), range(0)

As an empty list is in fact just an empty collection, it will be converted to a boolean value of False. Therefore, if py_list is empty, it will be converted to False.

The second statement is pretty similar, except not will invert a false condition to a true one. This approach is very similar to the if(len(list)) approach.

This is the preferred approach as it's the cleanest and shortest solution there is.

Using bool() Function

We can also use the bool() function to verify a list is empty:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

#As truth value testing says [] braces denotes false

if bool(py_list):
    print('List is not empty')
else:
    print('List is empty')

This is basically a manually implemented truth value test. So if the list is not empty the function will return True and if block will be executed.

This approach is less common as we can achieve the desired results even without using bool(), but it's not a bad thing to know how Python works under the hood.

Conclusion

This article was all about ways to check if our python list is empty or not. We started by exploring different techniques and finally looking into some parameters that we can use to make our judgment regarding which technique may work for us.

I can't say that this is the end as new Python updates may give rise to new and more improved coding styles. So it's better to keep exploring and keep learning.

Last Updated: February 20th, 2023
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Project

Building Your First Convolutional Neural Network With Keras

# python# artificial intelligence# machine learning# tensorflow

Most resources start with pristine datasets, start at importing and finish at validation. There's much more to know. Why was a class predicted? Where was...

David Landup
David Landup
Details
Course

Data Visualization in Python with Matplotlib and Pandas

# python# pandas# matplotlib

Data Visualization in Python with Matplotlib and Pandas is a course designed to take absolute beginners to Pandas and Matplotlib, with basic Python knowledge, and...

David Landup
David Landup
Details

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms