Do you want to know how you can check if the list is empty or not in Python? In this article, I will tell you the most efficient and inefficient ways to check if the given list is empty or not.
1. Using If and If Not Conditions of Python
If you are familiar with Python If conditions then you must know that using the If condition you can easily tell if the list is empty of not. Alternatively, you can use If not condition as well to verify the list.
Let us see in the below example code the usage of if and if not a condition.
#initializing an empty list givenList =  #Check if List is Empty using If Condition if givenList: print("List is not Empty") else: print("List is Empty and if conditin is used") #Check List is Empty using If Not Condition if not givenList: print("List is Empty and if not is used")
List is Empty and if conditin is used List is Empty and if not is used
Using the above code we got our desired result. But if your intent is to check only if the given list is empty or not it is more efficient to use the
if not condition as that makes more sense and is considered as best practice.
2. Comparing with Empty List to Check List is Empty
The second option but is not efficient as the first one is to compare the given list to an empty list as in this case it will return true and then you can continue any operation you like to perform.
Let us see in the below example code for comparing the given list with an empty list.
#initializing an empty list givenList =  #Comparing List with Empty List if givenList == : print("List is Empty")
List is Empty
3. Using Len Method of Python
In Python, there is len() method that is used to get the length or size of the given list. Hence once you perform len on the empty list you will get 0 as the return value. You can compare if the len return is 0 or not and then you can do your operation based on the return and verify that if the given list is empty or not.
Note that this method is not recommended as it is not pythonic to use such code and it is bad coding practice to follow.
#initializing an empty list givenList =  #Using Len to get the Len and COmparing if len(givenList) == 0: print("List is Empty")
List is Empty
4. Using Try and Except Method (Not Recommended)
This is another way to know if the list is empty or not but this method is completely silly and should not be used in production code. I am listing this method just for the purpose of knowledge.
#initializing an empty list givenList =  #Using Try and Except Method to check if List is Empty try: next(iter(givenList)) except StopIteration: print("Error: List is Empty")
Error: List is Empty
I hope you were able to know the answer on how to check if the list is empty in Python. I have listed around 4 methods that you can use to easily check the list in Python.
If you have any better method then please let me know in the comment section and I would be happy to add it here.