askvity

How to Check if a List is Empty in Python?

Published in Python List Check Empty 3 mins read

Checking if a list is empty in Python is a common task with several straightforward methods. The most Pythonic and widely used approach leverages the fact that empty sequences (like lists, tuples, strings, dictionaries, and sets) are considered "falsy" in a boolean context.

A list is empty if it contains no elements.

Common Methods to Check for an Empty List

Here are the primary ways to determine if a Python list is empty, incorporating information from the provided reference:

1. Using the len() Function

The len() function returns the number of items in a sequence. If the length of the list is 0, the list is empty.

  • How it works: You call len() on the list and check if the result is equal to 0.
  • Syntax: len(my_list) == 0
  • Example:
my_list = []
if len(my_list) == 0:
    print("The list is empty using len().")

another_list = [1, 2, 3]
if len(another_list) != 0:
    print("The list is not empty using len().")

2. Comparing to an Empty List

You can directly compare the list in question to an empty list literal [] using the equality operator ==.

  • How it works: Python checks if the contents of your list are identical to the contents of an empty list (which has no contents).
  • Syntax: my_list == []
  • Example:
my_list = []
if my_list == []:
    print("The list is empty by comparing to [].")

another_list = ['a', 'b']
if another_list != []:
    print("The list is not empty by comparing to [].")

3. Using Truthiness (The Pythonic Way)

In Python, empty sequences are considered "falsy" values. This means you can use a list directly in a boolean context (like an if statement) to check if it has any elements.

  • How it works: An empty list evaluates to False, while a non-empty list evaluates to True.
  • Syntax: not my_list (to check if it's empty) or if my_list: (to check if it's not empty)
  • Example:
my_list = []
if not my_list: # Equivalent to: if my_list is empty:
    print("The list is empty using truthiness.")

another_list = [10]
if another_list: # Equivalent to: if my_list is NOT empty:
    print("The list is not empty using truthiness.")

Comparing the Methods

Method Syntax Readability Performance Pythonic?
Using len() len(lst) == 0 Explicit, clear Generally fast Yes
Comparing to [] lst == [] Explicit, clear Generally fast Yes
Using Truthiness (not) not lst Concise, idiomatic Generally fastest Most

All three methods are valid and efficient for checking if a list is empty. The truthiness method (if not my_list:) is often preferred by experienced Python developers for its conciseness and idiomatic nature.

Related Articles