Skip to content
Back to 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.

Copyright notice

Unless otherwise stated, quietin owns the copyright in all articles. All rights reserved. Except as permitted by law or with prior written permission, reproduction or republication, in whole or in part, is prohibited. Permitted quotations must credit the author and link to the original article.