In this article, we will learn how to check whether a tuple is empty or not.
How to Check Empty Tuple in Python?
In python, tuples are written within round brackets. And are ordered and unchangeable. There are various ways to check for an empty tuple.
Let us discuss them one by one
Example 1: Using the not Operator
# Initializing an empty tuple
Mytuple=()
# Using not operator
if not Mytuple:
print ("Mytuple is empty")
else:
print ("Mytuple is not empty")
# Printing the tuple
print(Mytuple)
Output
Mytuple is empty
()
Explanation
In the above example, we created an empty tuple ‘Mytuple’. Then we used a not operator to reverse the false value. In python, an empty tuple always evaluates to false. So when we passed an empty tuple to the if condition it’ll be evaluated to false. But the not operator reverses the false value to the true value.
Thus the if condition is set to true. And we got “My tuple is empty” as an output.
Example 2: Using the len() Function
# Initializing an empty tuple
Mytuple=( )
# Using len() function
Length_Mytuple = len(Mytuple)
# Using if-else Statement
if Length_Mytuple == 0:
print ("Mytuple is empty")
else:
print ("Mytuple is not empty")
# Printing the tuple
print(Mytuple)
Output
Mytuple is empty
()
Explanation
In the above example, we initialized an empty tuple ‘Mytuple’. Then we used a built-in function len() to calculate the length of the tuple and stored it in the variable ‘Length_Mytuple’. Then we used if statement to check if the length of the tuple is equals to zero or not.
If the condition sets to be true then the tuple is empty. Otherwise the tuple is not empty.
Example 3: Comparing with Another Empty Tuple
# Initializing a tuple ‘MyTuple’
MyTuple = ('Hello','World')
# Initializing an empty tuple ‘MyTuple2’
MyTuple2 = ( )
# Comparing both the tuple
if MyTuple == MyTuple2:
print('MyTuple is empty!')
else:
print('MyTuple is not empty!')
Output
MyTuple is not empty!
Explanation
In the above example, we initialized two tuples MyTuple and MyTuple2. Suppose we have to check for if ‘MyTuple’ is empty or not. Then we can do so by initializing an empty tuple say ‘MyTuple2’.
And then comparing ‘MyTuple’ with ‘MyTuple2’ using the decision making statement i.e if-else condition. If ‘MyTuple’ is equal to ‘MyTuple2’ then that means ‘MyTuple’ is an empty tuple. Else it is not empty.
And this is how we can check for an empty tuple by comparing it with another empty tuple.
Conclusion
In this article, we saw three different ways to check for an empty tuple. The three ways we discussed above are:
- Using not
- Using len()
- Comparison with an empty string’