In this article, you will learn how to check if a list is empty or not using a Python program with simple understandable code.
In the Python programming language, there are multiple ways to check whether a list is empty. Below, we will see three ways to check if the list is empty or not with the sample code.
Checking if a list is empty or not
we are going to discuss three methods to check whether a list is empty or not
- Using Boolean Operation
- Using len()
- Comparing with ()
Example 1: Using Boolean Operation
mylist=[] if not mylist: print("list is empty") else: print("list is not empty")
Output: list is empty
Explanation of the code
- Here, we are giving the variable name as mylist, and we have it as an empty string. So, we are going to check whether the list is empty. If it is true, we are going to print a statement.
- In the second line, we are using the ‘not’ keyword as it is a Boolean operation. In this line, the control flow checks whether there are certain elements in a mylist variable and if it is not finding any of the elements in the mylist, it will return false.
Example 2: Using len()
We can also use the len() method in order to find the length of the list. If it returns 0, then the list will be empty, and if it returns non-o, then the list is not empty. Here we are giving some words in the string to print; the list is not empty.
mylist=["code","speedy"] if not len(mylist): print("list is empty") else: print("list is not empty")
Output: list is not empty
Example 3: Using with []
We can simply use square brackets to find out if the list is empty or not. In the below example, we are declaring the variable name as “a” and inserting some values in the string to find out whether the list is empty or not.
a=[5,6,7] if a==[]: print("The list is empty") else: print("The list is not empty")
Output: The list is not empty
Conclusion
In this article, you have learned the process of creating a simple python program to check if a list is empty or not, this is the basic python program you can modify with your specifications. Thank you for learning with us, Have a great journey