Open In App

Check if a list is empty or not in Python

Last Updated : 24 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In article we will explore the different ways to check if a list is empty with simple examples. The simplest way to check if a list is empty is by using Python's not operator.

Using not operator

The not operator is the simplest way to see if a list is empty. It returns True if the list is empty and False if it has any items.

Python
a = []
if not a:
    print("The list is empty")
else:
    print("The list is not empty")

Output
The list is empty

Explanation:

  • not a returns True because the list is empty.
  • If there were items in the list, not a would be False.

Using len()

We can also use len() function to see if a list is empty by checking if its length is zero.

Python
a = []
if len(a) == 0:
    print("The list is empty")
else:
    print("The list is not empty")

Output
The list is empty

Explanation: len(a) returns 0 for an empty list.

Using Boolean Evaluation Directly

Lists can be directly evaluated in conditions. Python considers an empty list as False.

Python
a = []
if a:
    print("The list is not empty")
else:
    print("The list is empty")

Output
The list is empty

Explanation: An empty list evaluates as False in the if condition, so it prints "The list is empty".


Practice Tags :

Similar Reads

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy