Last Updated on June 17, 2021 by Roshan Parihar
In this tutorial, learn how to check if the list is empty or not using Python. The short answer is: use the Python len()
with the if condition to find if the list is empty.
There are many methods from which 3 methods are given here to find if the list is empty list in Python. These methods are using len()
, if and boolean content, and bool()
.
Check whether a list is empty with the description and examples are given here. So, let’s start learning each method given below with examples.
Check If List is Empty with If and len() in Python
If you want to find the list if it is empty, you have to use the Python len()
. When checking if a list is empty in python, the length of the list is zero(0) in the output. It means the list is empty and there are no elements in the given list.
There is also an else statement with the if statement to print false output. If the list has some items, the output executes the code under the else statement.
1 2 3 4 5 |
myList = []; if len(myList)==0: print("The list is empty."); else: print("The list is not empty."); |
Output
The above example showing the empty list and the code to find whether the list is empty. The output prints the text showing that the list contains no elements and it is empty.
Python Check If List Is Not Empty With If and Boolean Context
The second method to check if list is not empty using the boolean context. To check if the list element is empty in python, you have to use the below-given example using the Python boolean not
statement. If the list contains no element, it executes the print function under the if condition.
1 2 3 4 5 |
myList = []; if not myList: print("The list is empty."); else: print("The list is not empty."); |
Output
The above example showing the above-given list of Python is empty. However, if the list is not empty, it executes the code under the else statement of Python.
Find Vacant List Using If and bool() in Python
In addition to the above all methods, you can also use the Python bool()
function. The bool function gives the output as False
, if the list is empty. But, if the list is not empty, the bool function given the output as True
.
You have to check the list if empty using the below-given example. Change the example as per your requirement to get the result.
1 2 3 4 5 |
myList = []; if bool(myList)==False: print("The list is empty."); else: print("The list is not empty."); |
Output
The above example prints the code under if condition, if the list is empty and bool function gives False
. Otherwise, it prints the code under the else statement if the bool function given True
.
DOWNLOAD Free PYTHON CHEAT SHEET
You may also like to read
- Learn how to create a list variable in Python
- Append or insert elements to list in Python
- Get list element by index in Python
- How to find the size of a list item using Python
I hope you like this post on how to check if the list is empty using Python.
References