How Does Tuple Comparison Work In Python?

A Quick Introduction To Tuples

Python consists of 4 built-in data types that are used to store collections of data. These data types are:

A tuple allows you to store multiple items within a single variable. Hence, it is a collection that is ordered and unchangeable/immutable. Also, tuples are heterogeneous as they allow you to store elements that are of different types.

Syntax:

my_tuple = (1, 2, 3, 'Python')

Example:

my_tuple = ("Python", "Java", 200)
print(my_tuple)

# OUTPUT : ('Python', 'Java', 200)

For more details on tuples in Python, please have a look at our blog tutorial here. The purpose of this article is to discuss how the comparison works between two tuples.

Problem Formulation

Given two tuples; how does the comparison between the two tuples work?

Example:

(4, 5) < (3, 5) # Equals false

So, as depicted in the above example – how/why is the output false? Or How does Python compare these two tuples?

🐍 Comparing Tuples – Python

👍 The Rule of Thumb for comparing Python Tuples:

Tuples in Python are compared lexicographically. This means that the corresponding elements of the given tuples are compared to each other.

Therefore, tuples in Python are compared on the basis of their position : the first item of the first tuple is compared to the first item of the second tuple. If they are not equal then the first comparison is enough to deduce the output. Otherwise the second items are considered, then the third and so on until all the corresponding elements of both the tuples have been compared.

Let us have a look at what the Python documentation talks about Value Comparison of built-in sequences like lists and tuples:

  • For two collections to be “equal”:
    • they must be of the same type, (for example, [10,20] == (10,20) is false because the type is not the same).
    • they must have the same length, and
    • each pair of corresponding elements in the given sequences must be equal.
  • Tuples support order comparison and collections that support order comparison are ordered the same as their first unequal/differing elements.
    • For example, [10,20,a] <= [10,20,z] is the same as a <= z). In case a corresponding element doesn’t exist, then the shorter collection is ordered first and is considered smaller. (for example, [10,20] < [10,20,0] is true).

⚠️ Attention

  • You should not consider Tuples as vectors in an n-dimensional space, compared according to their length.
  • In ordered comparisons, < and > do not represent “smaller than” and “greater than“; rather they represent “is before” and “is after“. So in our example above (4, 5) is not before (3, 5). Hence, the output is False.

Now let us have a look at few scenarios that will further clarify our concept.

➧Normal Comparisons

Let us have a look at the following snippet which compares two tuples in numerous scenarios:

# comparing integers
print((10, 20) < (10, 25))
print((10, 20) == (10, 25))
print((10, 20) > (10, 25))
# comparing strings
print(('x', 'y') < ('x', 'z'))
# comparing list of tuples
print(([4, 5], [5, 6]) == ([4, 5], [5, 6]))

Output:

True
False
False
True
True

Explanation:-

  • While comparing (10,20) and (10,25) it is observed that the first element in both the tuples are equal, hence the next elements are compared and it is evident that 20 < 25. This means that (10,20) < (10,25).
  • (‘x’, ‘y’) < (‘x’, ‘z’) is true because when you compare the ASCII values of the second element of the two tuples then you have the following output: ord('y')< ord('z') # --> true
  • Similarly, in the third scenario, it is quite clear that when we compare the two tuples containing similar lists, the output is true.

➧Comparing Unequal Tuples

Consider that you have couple of tuples with different lengths. Let us have a look at how this comparison works in the following snippet:

tup1 = (10, 20, 30)
tup2 = (10, 20, 30, 40)
if tup1 > tup2:
    print(tup1, ">", tup2, "--> TRUE")
else:
    print(tup1, '<', tup2, "--> TRUE")

Output:

(10, 20, 30) < (10, 20, 30, 40) --> TRUE

➧Comparing Tuples With Heterogeneous Items

While comparing two tuples that have heterogeneous items, that is, == operator functions normally; however < and > operators do not work with heterogenous data-types.

Example:

print(('5',1,2)==(6,1,2)) # ---> False
print(('5',1,2)>(6,1,2)) # --> TypeError: '>' not supported between instances of 'str' and 'int'

Therefore to evaluate greater than and less than operators for comparing heterogeneous items of two tuples, you have to use the map() function to convert the values in both the tuples into a single type. You can read about the map() function in this tutorial.

Example:

tup1 = (10, 20, 30)
tup2 = ('100', 20, 30)
print(tuple(map(int, tup2)) > tup1)

Output:

True

🎁 Bonus: Methods To Compare Two Tuples In Python

➧ Method 1 : Using all() and zip()

  • Python’s built-in all(x) function takes one iterable as an argument x such as a list, tuple, or dictionary. It returns True if all iterable elements evaluate to True using implicit Boolean conversion, otherwise, it returns False. If the iterable is empty, all() returns True because the condition is satisfied for all elements.
  • The zip() function takes an arbitrary number of iterables and aggregates them to a single iterable, a zip object. It combines the i-th values of each iterable argument into a tuple. Hence, if you pass two iterables, each tuple will contain two values. If you pass three iterables, each tuple will contain three values. For example, zip together lists [1, 2, 3] and [4, 5, 6] to [(1,4), (2,5), (3,6)].

Example:

tup1 = (10, 20, 40)
tup2 = (5, 15, 25)
if all(x > y for x, y in zip(tup1, tup2)):
    print("tup1 is greater!")
else:
    print("tup2 is greater!")

Output:

tup1 is greater!

➧ Method 2 : Using all() And map() With A Lambda Function

tup1 = (10, 20, 40)
tup2 = (5, 15, 25)
if all(map(lambda x, y: x>y,tup1, tup2)):
    print("tup1 is greater!")
else:
    print("tup2 is greater!")

Output:

tup1 is greater!

Conclusion

I hope this article helped you to understand tuple comparisons in Python. Please subscribe and stay tuned for more interesting concepts and discussions.