Python Program to Check If a List is Empty


10xer.co Ad Sponsored

ⓘ Sponsored by 10xer.co

In Python, a list is a collection of items that are ordered and changeable. Lists are one of the most versatile data structures in Python, and they can contain elements of different types such as integers, floats, strings, and even other lists. You can create a list using square brackets [] or by using the built-in list() function.

Here’s an example of creating a list:


my_list = [1, 2, 3, "apple", "banana", "cherry"]

You can access individual elements in a list using their index, starting from 0 for the first element.


Python Code :

The below Python program checks if a list is empty:


# Define an empty list
my_list = []

# Check if the list is empty using bool()
if not bool(my_list):
    print("The list is empty.")
else:
    print("The list is not empty.")

Output:


The list is empty.

In this program, we first define an empty list called my_list.

We then check if the list is empty using the bool() function. In Python, an empty list evaluates to False when converted to a boolean value, so we use the not operator to invert the result of the conversion. If the list is empty, the not operator will convert it to True, and the message “The list is empty.” will be printed. If the list is not empty, the message “The list is not empty.” will be printed.

Alternatively, you can check if a list is empty by using the len() function. In Python, an empty list has a length of 0, so you can check if the length of the list is equal to 0:


if len(my_list) == 0:
    print("The list is empty.")
else:
    print("The list is not empty.")

Both of these methods will give you the same result.


10xer.co Ad Sponsored

ⓘ Sponsored by 10xer.co