- Not Operator
- The len() function
- Comparison with an Empty List
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.
- This way is computationally faster than all other ways
- It may seem like the list is Boolean
empty_list =  if not empty_list: print('The list is empty!') else: print('The list is not empty.')
The len() Function
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.
- It is easy to understand
- This way is computationally slower than other ways.
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.
- This way is easy to understand
- It is also computationally slower
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.