How to Check if a List is Empty in Python

Lists are one of the most common data types you’ll be using if you start coding with Python. One of the usual checks you may have to perform is to check if a list is empty. In this tutorial, we’ll see the many solutions you have at your disposal to check if a list is empty.

Use the len() function to check if a list is empty

The most simple and common ways to perform this operation is to use the built-in len() function which returns the number of items of an object. If you use it with a comparison operator, you’ll be able to know if a list is empty.

my_list = [1,2,3,4,5] my_empty_list = [] def check_if_empty(list): if len(list)==0: print('The list is empty') else: print('The list is not empty') print(check_if_empty(my_list)) print(check_if_empty(my_empty_list))
Code language: Python (python)

Output:

The list is not empty The list is empty
Code language: PHP (php)

Use implicit boolean to check if a list is empty

While the previous solution is the simplest, it is not the more pythonic. Our previous code can be slightly modified to achieve the same (we just modified the highlighted line):

my_list = [1,2,3,4,5] my_empty_list = [] def check_if_empty(list): if list: print('The list is empty') else: print('The list is not empty') print(check_if_empty(my_list)) print(check_if_empty(my_empty_list))
Code language: Python (python)

We leverage the fact that empty sequences (strings, lists, tuples) are False. Hence, if list will return False if the list is empty. This structure is recommended by the PEP 8 style guide. That being said, if you’re learning, I’d rather use the first “wrong” structure because the condition is not implicit.

# Correct: if not seq: if seq: # Wrong: if len(seq): if not len(seq):
Code language: Python (python)

As explained, the output will be the same:

The list is not empty The list is empty
Code language: PHP (php)

Leave a Reply

Your email address will not be published. Required fields are marked *