Last Updated On By Anmol Lohana
In Python, lists are evaluating as false when the list object is empty and true when the list is not empty in Boolean context. Hence, we can deal with lists as predicate returning a Boolean value. This process is fully pythonic and recommended.
Table of Contents
As we saw above, that evaluation of an empty list is false so, when we apply not-operator on false, it will become true, and it will run the statement inside of if condition.
empty_list = []
if not empty_list:
print('The list is empty!')
else:
print('The list is not empty.')
The len() function is a builtin function and is use to find the length of a list. If it returns 0, it means the list is empty.
empty_list = []
if len(empty_list) == 0:
print('The list is empty!')
else:
print('The list is not empty.')
Another way to find an empty list is to compare an empty list with the given list and know that it is empty.
empty_list = []
compare_with = []
if empty_list == compare_with:
print('The list is empty!')
else:
print('The list is not empty.')
In conclusion, we discussed Python checks if a list is empty or not. The list is a data structure that stores data in Python. We saw three different ways to find it with coding examples. Using not operator to turn Boolean false value into true, using len() function to find the length of the list, and the comparison method to compare given list with an empty list.