Last Updated : 24 Oct, 2024
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 operatorThe 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")
Explanation:
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")
Explanation: len(a) returns 0 for an empty list.
Using Boolean Evaluation DirectlyLists 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")
Explanation: An empty list evaluates as False in the if condition, so it prints "The list is empty".
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4