Python – Check If a List Is Empty

The list is a popular type in Python programming language and it may contain no, single or more items. In some cases, we may need to check if the given list is empty. In this tutorial, we will examine different methods to check the list emptiness.

Use not Operator with if Conditional

Python List provides some features like empty list is evaluated into False for boolean check and True if the list has single or more items. This boolean way of the list can be used with the if conditional to check if the specified list is empty. Also this method is the most pythonic and recommended way to check the list emptiness which is recommended in PEP8 style guide. We will also use the not operator because the empty list returns False but to execute if conditional it should be True where we will reverse the empty list False value into True.

mylist= []

if not empty_list: 
   print("Provided list is empty")

Alternatively we can not use the not operator instead add an else into the if conditional where the else will be executed if the given list is empty.

mylist= []

if mylist: 
   print("Provided list is NOT EMPTY")
else:
   print("Provided list is EMPTY")

We can also check the list emptiness after adding some elements to the empty list. The output will be “This list is NOT EMPTY” for the following examle.

mylist= [1,2,3]

if mylist: 
   print("Provided list is NOT EMPTY")
else:
   print("Provided list is EMPTY")

Return Item Counts with len() Method

Python provides the len() method which is used to return the item count for the provided sequential type. As the list is a sequential type too this len() method can be used to return the item count and if the returned item count is 0 this means the list is empty. We can compare the item count of the list with 0 like below.

mylist= []

if len(mylist)==0: 
   print("Provided list is EMPTY")

We can also use the boolean logic of the 0 which will be evaluated into False. Byt using the not operator following if conditional can be used without a comparison.

mylist= []

if not len(mylist): 
   print("Provided list is EMPTY")

Compare with Empty List

The last method to check if the specified list is empty is comparing specified list with and empty list. If they are equal this statement returns True which can be used in if conditional.

mylist= []

if mylist == []:
   print("Provided list is EMPTY")

Leave a Comment