Last modified: Jan 10, 2023 By Alexander Williams
How to Properly Check if a List is Empty in Python
in this article, we'll learn the best way to check if a list is empty.
Checking if the list is empty [Good way]
Example 1
#list
list_1 = []
#checking if the list is empty
if not list_1:
print('yes! the list is empty.')
else:
print('No! the list has items')
output
'yes! the list is empty.'
Example 2
#list
list_1 = [1, 2, 3, 4]
#checking if the list is empty
if not list_1:
print('yes! the list is empty.')
else:
print('No! the list has items')
output
No! the list has items'
Checking if the list is empty [Bad way]
Example 1
#list
list_1 = []
#checking if the list is empty
if len(list_1) == 0:
print('yes! the list is empty.')
else:
print('No! the list has items')
output
'yes! the list is empty.'
Example 2
#list
list_1 = [1, 2, 3, 4]
#checking if the list is empty
if len(list_1) == 0:
print('yes! the list is empty.')
else:
print('No! the list has items')
As you can see, the code is working, but this is the worst way to do that because you don't need to use len() function to check if a list is empty.
your code should be short, clean and fast.