Python check empty list

This article will explore different ways to check if list is empty in python with example programs.

Method 1: Using len() function
Python len() function is used to find the length of a list or the number of elements in it.
For empty list, len() will return 0. So, to check if list is empty or not, compare the return value with 0 as shown below.

l = []
if len(l) == 0:
   print('List is empty')

Comparison with 0 can be skipped when using len(). So, above code can be shortened to

l = [] 
if len(l): 
  print('List is empty')

PEP(Python Enhancement Proposal) 8 does not recommend this syntax.
Method 2: Checking empty sequence
PEP 8 states that empty sequences(strings, lists or tuples) are False. So, empty list is False and non-empty list is True.

Below syntax checks if a list is empty in python

l = [] 
if not l: 
  print('List is empty')

Applying not before empty list makes it True, so the if test passes.
This syntax is recommended by PEP 8.

To check for non-empty list, use below code

l = [1] 
if l: 
  print('List is not empty')

Method 3: Compare with empty list
Compare the list to be checked with an empty list using == operator.
If the list to check is empty, it will return True as shown below

list_to_check = []
empty_list = []
if list_to_check == empty_list:
   print('List is empty')

That is all on different ways to check if list is empty in python. Hope the article was helpful.

Liked the article ? Spread the word...