my_list = list()
# Check if a list is empty by its length
if len(my_list) == 0:
pass # the list is empty
# Check if a list is empty by direct comparison (only works for lists)
if my_list == []:
pass # the list is empty
# Check if a list is empty by its type flexibility **preferred method**
if not my_list:
pass # the list is empty
# For sequences, (strings, lists, tuples), use the fact that empty sequences are false:
# Correct:
if not seq:
if seq:
# Wrong:
if len(seq):
if not len(seq):
my_list = list()
# Check if a list is empty by its length
if len(my_list) == 0:
pass # the list is empty
# Check if a list is empty by direct comparison (only works for lists)
if my_list == []:
pass # the list is empty
# Check if a list is empty by its type flexibility **preferred method**
if not my_list:
pass # the list is empty
how to use python all() function to check a list is empty or not
emptyList = [1]
length = len(emptyList)
if length == 0 and all(emptyList):
print("This list is empty now.")
else:
print("This list is not empty.
The values of list:")
for x in emptyList:
print(x)
Check if list is empty in Python Using the len() method
code
# empty list & non-empty list
empty_list = []
non_empty_list = [1, 2, 3, 4]
# check if list is empty
def check_list_empty(lst):
if len(lst) == 0:
print('The List is empty')
else:
print('The list is not empty')
# pass in the lists to check_list_empty
check_list_empty(empty_list)
check_list_empty(non_empty_list)
#Output
The list is empty
The List is not empty