How to Check if a Python List Is Empty?
You can check if a Python list is empty using the following ways:
- Using len() function:
You can use the len() function to check if the length of the list is 0. If the length is 0, it means the list is empty. Here’s an example:
my_list = []
if len(my_list) == 0:
print("Empty list")
else:
print("Not empty list")
Output:
Empty list
- Using not operator:
You can use the not operator to check if the list is empty. If the list is empty, the condition will evaluate to true. Here’s an example:
my_list = []
if not my_list:
print("Empty list")
else:
print("Not empty list")
Output:
Empty list
- Using if statement:
You can also use the if statement to check if the list is empty. If the length of the list is 0, the if statement will evaluate to false. Here’s an example:
my_list = []
if my_list:
print("Not empty list")
else:
print("Empty list")
Output:
Empty list