Checking with if not
In Python, an empty sequence (an empty list) is considered False, so you can use the if not operator to check if a list is empty.# Check if the list is empty
if not emptyList:
print('The list is empty')
Reversing the condition
# Reverse the condition
if emptyList:
print('The list is not empty')
else:
print('The list is empty')
Note
Since None is also considered False, if you want to strictly compare None and an empty list, you can use the “is None” operator to check.Checking for an empty list considering None
# Checking for an empty list considering None
if emptyList is None:
print('It is None')
elif not emptyList:
print('The list is empty')
Checking with the built-in len function
If you pass a list to the len function, it returns the number of elements in the list. If the len function returns zero, the list is empty.# Check with the len function
if len(emptyList) == 0:
print('The list is empty')
Comparing with an empty list
The previous methods also consider numeric zero and an empty string as true. To prevent this, compare it to an empty list.# Compare with an empty list
if emptyList == []:
print('The list is empty')
References
- Python Official Documentation - Truth Value Testing
- Python Official Documentation - Built-in Functions - len
Test Environment
- Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win32
- Microsoft Windows 10 Pro Version 1809 OS Build 17763.439