search

How to check if a tuple is empty in Python?

To check if a tuple 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_tuple = ()  # Empty tuple
if not my_tuple:
    print("The tuple is empty")
else:
    print("The tuple is not empty")

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

Using the len() function:

my_tuple = ()  # Empty tuple
if len(my_tuple) == 0:
    print("The tuple is empty")
else:
    print("The tuple is not empty")

In this example, the len() function is used to get the length of the tuple my_tuple. If the length of the tuple is equal to 0, indicating that there are no elements in the tuple, the condition len(my_tuple) == 0 evaluates to True, and the message "The tuple is empty" is printed. Otherwise, if the length of the tuple is not equal to 0, the condition evaluates to False, and the message "The tuple 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