xxxxxxxxxx
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
xxxxxxxxxx
# 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):
xxxxxxxxxx
emptyList = [1]
length = len(emptyList)
if length == 0 and all(emptyList):
print("This list is empty now.")
else:
print("This list is not empty.\n\nThe values of list:")
for x in emptyList:
print(x)
xxxxxxxxxx
numbers = []
if not numbers:
print("The list is empty")
else:
print("The list is not empty")
# The list is empty
xxxxxxxxxx
l = []
if len(l) == 0:
print("the list is empty")
l = []
if l:
print("the list is not empty")
else:
print("the list is empty")