How can I check if a list is empty in Python without using len()?
Ava W
ava w profile pic

To check if a list is empty in Python without using thelen() function, you can utilize the fact that empty lists are considered "falsy" in Python, meaning they evaluate toFalse in a boolean context. Here are a few approaches you can use: 1. Using the not operator: You can use thenot operator to check if the list is empty. Thenot operator negates the truth value of an expression, so by applying it to the list, you can determine if the list is empty.

1
2
3
4
5
6
7

my_list = []

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

Output:

The list is empty.

In this example, thenot operator is applied tomy_list, and since the list is empty, the condition evaluates toTrue, indicating that the list is empty. 2. Using the equality operator with an empty list: You can directly compare the list to an empty list using the equality (==) operator to determine if it is empty.

1
2
3
4
5
6
7

my_list = []

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

Output:

The list is empty.

In this example, themy_list is compared to[], the empty list, and the condition evaluates toTrue since they are equal. 3. Using the any() function: Theany() function can be used to check if any elements exist in the list. If the list is empty, the function returnsFalse, and if there are any elements present, it returnsTrue.

1
2
3
4
5
6
7

my_list = []

if not any(my_list):
    print("The list is empty.")
else:
    print("The list is not empty.")

Output:

The list is empty.

In this example, theany() function is applied tomy_list, and since there are no elements in the list, the condition evaluates toTrue, indicating that the list is empty. Summary: To check if a list is empty in Python without using thelen() function, you can utilize the fact that empty lists are considered "falsy" in Python. By using thenot operator, comparing to an empty list, or applying theany() function, you can determine if the list is empty. These methods provide alternative approaches to check for an empty list and help you handle empty list scenarios in your Python code.