How do we compare two tuples in Python?

Tuples are compared position by position: the first item of the first tuple is compared to the first item of the second tuple; if they are not equal, this is the result of the comparison, else the second item is considered, then the third and so on.

Lexicographic Comparison

Python compares tuples element by element from left to right using lexicographic ordering ?

a = (1, 2, 3)
b = (1, 2, 5)
print(a < b)
print(a == b)
print(a > b)
True
False
False

In this example, the first two elements are equal (1, 2), so Python compares the third elements: 3 a return True.

Different Length Tuples

When tuples have different lengths, the shorter tuple is considered smaller if all its elements match the beginning of the longer tuple ?

short = (1, 2)
long = (1, 2, 3)
print(short < long)
print(short == (1, 2))
True
True

Finding Common Elements Using Sets

To find similar elements between tuples, convert them to sets and use intersection operations ?

a = (1, 2, 3, 4, 5)
b = (9, 8, 7, 6, 5)
common = set(a) & set(b)
print(common)
{5}

Using set.intersection() Method

The intersection() method provides an alternative way to find common elements ?

a = (1, 2, 3, 4, 5)
b = (9, 8, 7, 6, 5)
common = set(a).intersection(set(b))
print(common)
{5}

Comparison Methods Summary

Method Use Case Result Type
Direct comparison (<, >, ==) Lexicographic ordering Boolean
set(a) & set(b) Common elements Set
set(a).intersection(set(b)) Common elements Set

Conclusion

Use direct comparison operators for ordering tuples lexicographically. Use set operations to find common or different elements between tuples.

Updated on: 2026-03-24T20:22:05+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements