python

How to check if a list is empty in Python

In this tutorial, we are going to see different ways to check if a list is empty in Python. Either by using the “not” operator or by using the “len()” function. As shown below.
 

How to check if a list is empty using the “not” operator

“not” operator in Python can be used to check if a list is empty. for example:

# Empty lists are evaluated to False
list = [] 
if not list:
    print ("List is empty")
else:
    print ("List is not empty")

Output:

List is empty
 

How to check if a list is empty using “len()” function

The len() function returns the number of elements of an object.

list = [] 
# len() returns the number of elements in a list
if len(list) == 0:
    print ("List is empty")
else:
    print ("List is not empty")

Output:

List is empty
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *