Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
December 24, 2022 10:00 pm GMT

How to check if a tuple is empty in Python?

Just like lists, tuples are also a sequence of values and are considered falsy if they are empty. So, if you want to check if a tuple is empty, you can simply use the not operator.

empty_tuple = ()non_empty_tuple = (1, 2, 3)not empty_tuple # Truenot non_empty_tuple # False

In the above code example, we can see that the not operator returns True if the tuple is empty and False if the tuple is not empty. The not operator is a unary operator that returns the opposite of the value it is applied to. Using the not operator is considered the most Pythonic way to check if a object is empty.

There are other ways to check if a tuple is empty. For example, you can use the len() function. This function returns the length of the tuple, which is 0 if the tuple is empty.

empty_tuple = ()non_empty_tuple = (1, 2, 3)len(empty_tuple) == 0 # Truelen(non_empty_tuple) == 0 # False

One more way to check if a tuple is empty is to compare the tuple to an empty tuple using the == operator.

empty_tuple = ()non_empty_tuple = (1, 2, 3)empty_tuple == () # Truenon_empty_tuple == () # False

Original Link: https://dev.to/trinityyi/how-to-check-if-a-tuple-is-empty-in-python-2ie2

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To