0Pricing
Competitive Programming Academy · Lesson

Sort by Multiple Fields

Tie-break with tuple keys and reverse.

When One Key Is Not Enough

Sometimes items tie on the first field and you must break the tie. The fix is a tuple key that lists fields in priority order.

Tuples Compare Left to Right

Python compares tuples element by element: it checks the first item, and only looks at the second when the first ties.

print((1, 9) < (1, 2))   # False
print((1, 2) < (2, 0))   # True

All lessons in this course

  1. sorted() and the key Function
  2. Sort by Multiple Fields
  3. Custom Order with functools.cmp_to_key
  4. Why Sorting First Unlocks Solutions
← Back to Competitive Programming Academy