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
Published on 02-Jan-2018 23:22:41
Advertisements