In this article, we will learn how to check whether a list is empty or not. There are various ways to check for an empty list. To help us find an empty list we will take help of if-else statement and few built-in function.
We can check if Python list is empty using:
Let us understand it briefly with the help of an example.
Example 1: Using the not operator
# Initializing an empty list
MyList=[ ]
# Using not operator
if not MyList:
print ("MyList is empty")
else:
print ("MyList is not empty")
# Printing the list
print(MyList)
Output
MyList is empty
[]
Explanation
In the above example, we created an empty list ‘MyList’. Then we used a not on if condition. In python, an empty data structure(list, tuple, dictionary etc)always evaluates to false. So when we passed an empty list to the if condition it’ll be evaluated to false. But the not operator reverses the false value to true value. Thus the if condition is set to true. And we got “My List is empty” as an output.
Example 2: Using the len() function
# Initializing an empty list
MyList=[ ]
# Using len() function
Length_MyList = len(MyList)
# Using if-else Statement
if Length_MyList == 0:
print ("MyList is empty")
else:
print ("MyList is not empty")
# Printing the list
print(MyList)
Output
MyList is empty
[]
Explanation
In the above example, at first, we initialized the list ‘MyList’. Then we used a built-in function len() to calculate the length of the list and is stored in the variable ‘Length_MyList ’. Then we used if statement to check if the length of the list equals to zero or not. If the condition sets to be true then the list is empty. Otherwise, the list is not empty.
Conclusion
In this article, we have discussed two ways to check for an empty list. But among the two which one should we use?
The answer is quite simple. When using the built-in function len() we are first computing the length of the list and then checking for the empty list. So overall there are two operations being performed.
But in not operator we are directly checking for an empty list. That is only operation is being performed. Hence using the not operator would be a better choice