# 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
# to check if the list is empty use len(l) or not
l = []
if len(l)==0:
print("list is empty")
#or
if not l:
print("list is empty")
l1 = ["Hire", "the", "top", "1%", "freelancers"]
l2 = []
if l2:
print("list is not empty")
else:
print("list is empty")
#Output: "list is empty"
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")
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