search

How to check if a list is empty in Python?

To check if a list is empty in Python, you can use a simple condition using the not operator or the len() function. Here are two common approaches:

Using the not operator:

my_list = []  # Empty list
if not my_list:
    print("The list is empty")
else:
    print("The list is not empty")

In this example, the not operator is used to check if the list my_list is empty. If the list is empty, the condition not my_list evaluates to True, and the message "The list is empty" is printed. If the list is not empty, the condition evaluates to False, and the message "The list is not empty" is printed.

Using the len() function:

my_list = []  # Empty list
if len(my_list) == 0:
    print("The list is empty")
else:
    print("The list is not empty")

In this example, the len() function is used to get the length of the list my_list. If the length of the list is equal to 0, indicating that there are no elements in the list, the condition len(my_list) == 0 evaluates to True, and the message "The list is empty" is printed. Otherwise, if the length of the list is not equal to 0, the condition evaluates to False, and the message "The list is not empty" is printed.

Both approaches achieve the same result, so you can choose the one that suits your coding style and preference.

Related Questions You Might Be Interested