How to check if a list is empty in python?

A list is a sequence of elements separated by commas and enclosed within square brackets []. A list without any data items is an empty list. For example list_1 = [ ] is an empty list.

This article discusses several ways to check if a list is empty in python.

Checking if a list is empty by using the len() function

The len() function calculates the number of data items present in the list. If the length of the list is 0, the list is empty else the list is not empty.

Consider a list, list_1 = [1, 2, 3]. len(list_1) calculates the length of the list_1 and returns the value to 3 variable length. The value of length is not equal to 0. Hence, else block is executed and the output is printed.

list_1 = [1, 2, 3]
print("list_1: ", list_1)
length = len(list_1)
print("length : ", length)
if length == 0:
   print("Empty List")
else:
    print("List is not Empty")

Output

list_1:  [1, 2, 3]
length :  3
List is not Empty

Checking if a list is empty by using the not operator

The not-operator returns a boolean value. An empty list is evaluated to False in Python. Hence not-operator followed by an empty list returns True.

Consider a list, list_1 = []. If the list is empty the not operator returns a True Boolean value. Hence, if block is executed. If the list is not empty not-operator returns False which leads to execution of the else block.

list_1 = []
print("list_1 = ", list_1)
if not list_1:
    print("Empty List")
else:
    print("List is not Empty")

Output

list_1 =  []
Empty List

Checking if a list is empty by comparing it with an empty list

A list can be compared with an empty list by using the == operator. If the comparison returns True the list is an empty list else the list is not empty.

Consider a list, list_1 = [1, 2, 3]. The list_1 is compared with empty list [] using == operator. The comparison returns False. Hence, else block is executed and output is printed.

list_1 = [1, 2, 3]
print("list_1 = ", list_1)
if list_1 == []:
    print("Empty List")
else:
    print("List is not Empty")

Output

list_1 =  [1, 2, 3]
List is not Empty
0 results
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions