Skip to content
All Posts

Comparing Tuples in Python

An explanation of Python's lexicographic tuple comparison rules, including what happens when tuple lengths differ.

I recently came across this expression:

(2, 4) < (3, -1)
# True

It was not immediately obvious to me, so I looked it up. Python compares two tuples element by element, starting at the first position. When two elements differ, their comparison determines the result for the entire tuple. If they are equal, Python continues with the next position.

What happens when the leading elements match, but one tuple contains more elements?

(2, 4, -8) > (2, 4)

The answer is True: by default, the longer tuple is considered greater once all shared elements compare equal.

This behavior is useful in some sorting scenarios.


Originally published on SegmentFault.