How to check if a list is empty in Python?



In Python, empty list object evaluates to false. Hence following conditional statement can be used to check if list is empty.

>>> a=[] # Empty lists evaluate to False
>>> if not a:
    print ("list is empty")
else:
    print ("list is not empty")

You can also use len() function. It returns number of elements in a sequence. If len() returns zero, the list is empty

>>> if len(a)==0:
    print ("list is empty")
else:
    print ("list is not empty")
raja
Updated on 18-Feb-2020 10:19:40

Advertisements