Skip to content
Home / Fundamentals

How do I check if a list is empty?

TL;DR

use len(my_list) to check if your list is empty

Context

You have a list or tuple variable. You would like to check if your container is empty before proceeding with your actual code logic.

Remember Me
  • len() returns the number of items in a container
  • len()'s usage is not restricted to a list, but you can also use it for a tuple, dict, etc.

Examples

# Calculate the total amount to pay from the items
# Throw an error if items is empty
def prepape_payment(items: Sequence[int]) -> int :
    if len(items) == 0:
        raise Exception("No items were added to the basket")

    return sum(items)
# Check if a list is empty and print statements accordingly
def is_empty(some_list: Sequence[int]):
    if not len(my_list):
        print("This list is empty")
        return
    print("This list is not empty")

>>> my_list = []
>>> is_empty(my_list)
This list is empty

Why "if len()" instead "not <my_list>"

if not my_list appears to be the more pythonic way of writing code than using if len(my_list) == 0. However, pythonic does not always translate to being best practice. You should keep in mind that code is often read by more than one person and you should, therefore, look to be as explicit as possible.

def is_empty(collection):
    if not collection:
        print("I'm empty")
        return
    print("I'm not empty")

>>> my_list = []
>>> is_empty(my_list)
I'm empty
>>> is_empty(None)
I'm empty

The code is valid for both function calls. However, was is_empty(None) really intended? The function name is_empty would suggest otherwise. We want to check for where cases where collection is empty and not when it is None.

def is_empty(collection):
    if len(collection):
        print("I'm empty")
        return
    print("I'm not empty")

>>> my_list = []
>>> is_empty(my_list)
I'm empty
>>> is_empty(None)
ValueError

Here the updated is_empty function is much more explicit and is in sync with the function name. If you now pass in the None value, then the function will throw an error.