DEV Community

Cover image for How to check if a tuple is empty in Python?
Isabelle M.
Isabelle M.

Posted on

7

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 # True
not non_empty_tuple # False
Enter fullscreen mode Exit fullscreen mode

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 # True
len(non_empty_tuple) == 0 # False
Enter fullscreen mode Exit fullscreen mode

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 == () # True
non_empty_tuple == () # False
Enter fullscreen mode Exit fullscreen mode

Heroku

Amplify your impact where it matters most — building exceptional apps.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (1)

Collapse
 
rohit254 profile image
Rohit Kumar • Edited

Python tuple operations are very similar to Python lists therefore I think all operations that work on tuple can also work with Python lists and vice-versa. The blog explains things very clearly and easily.

I need suggestions on my blogs on list and tuple. Here is the link: -
[surushatutorials.blogspot.com/2024...]

Neon image

Set up a Neon project in seconds and connect from a Python application

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started →

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay