Specifically, we will go over the following methods:
# Using bool() function to check emptiness
if not bool(my_list):
print("The list is empty.")
# else block
else:
print("The list is not empty.")
The following output will be displayed in the console:
# Using len() function to check emptiness
if len(my_list) == 0:
print("The list is empty.")
else:
print("The list is not empty.")
In this example, the output will be “The list is empty.” because my_list doesn’t contain any elements.
my_list = [0, False, "", None] # A list with falsy values
# Using filter() function to check for emptiness based on truthiness
filtered_list = list(filter(lambda x: x, my_list))
if not filtered_list:
print("The list is empty or contains only falsy values.")
else:
print("The list is not empty.")
In this example, we have some constants defined in
my_list.
The output will be “The list is empty or contains only falsy values.”, because while my_list does have elements, all of them are considered false values.
# Using set comparison to check for emptiness
if set(my_list) == set():
print("The list is empty.")
else:
print("The list is not empty.")
In this example, the output will be “The list is empty.” because my_list does not contain any elements.
def is_empty(lst):
"""Return True if the list is empty, otherwise return False."""
return not lst
my_list = []
# Using the custom function to check for emptiness
if is_empty(my_list):
print("The list is empty.")
else:
print("The list is not empty.")
In this example, the custom function is_empty checks the truthiness of the list and returns the result.
The output will be “The list is empty.” because my_list doesn’t have any elements.