Concepts / Sorting Lists of Tuples

Sorting Lists of Tuples

The comparison is decided by the first unequal pair, not by the largest value anywhere in either tuple.

  • Programming
Interactive lab

Try it: Tuples: Comparison and Unpacking

How Python compares tuples lexicographically — the first unequal pair of items decides, a shorter prefix is smaller, int vs str ordering raises TypeError — and how tuple assignment unpacks and swaps values.

How it works

  1. Walk both tuples from index 0 while the items are equal.
  2. At the first difference, that pair alone decides (later items are never looked at); strs compare by code point.
  3. If one tuple runs out first, the shorter one is smaller; ordering an int against a str raises TypeError.
  4. Unpacking checks the count first: too many or too few values raise ValueError before any name is bound.
  5. a, b = b, a builds the right-hand tuple from the old values, then unpacks it into the names.

Default run (4 steps): Evaluate (1, 'pear', 7) < (1, 'plum', 2): compare item by item from index 0. … 'pear' < 'plum' is True (strings compare by code point: 'e' is 101, 'l' is 108), so (1, 'pear', 7) < (1, 'plum', 2) is True.

Simplified: Flat tuples of up to 6 ints or short ASCII strs (no nested tuples, floats or starred targets).

Educational simulation

Loading the simulation…

The First Difference

When Python compares two tuples, it does not treat each tuple as one indivisible object. It examines corresponding elements from left to right: first index 0, then index 1, then index 2, and so on. As soon as it finds a pair of unequal elements, that pair determines the comparison result. Python stops there and ignores every later element.

000011332000000later value4later valueequal, continuenot reachedequal, continuenot reached
How does Python move through corresponding tuple positions, and what happens when it finds the first unequal pair?
Key point

The comparison is decided by the first unequal pair, not by the largest value anywhere in either tuple.

A Comparison Trace

Worked example

Finding the stopping index

Compare the tuples (0, 1, 2000000) and (0, 3, 4).

  1. 1
    Index 0

    The values are 0 and 0. They are equal, so Python continues to the next position.

  2. 2
    Index 1

    The values are 1 and 3. They differ, and 1 is less than 3. This determines that the first tuple is less than the second.

  3. 3
    Index 2

    Python does not use 2000000 and 4 to decide the result because the comparison already stopped at index 1.

Result

(0, 1, 2000000) is less than (0, 3, 4).

Index 00 and 0Index 11 and 3First tuple less1 < 3Index 2not comparedequaldifferentstop before
At which index does Python stop comparing, and which values determine the final result?

Equal Prefixes

Tuple length matters only after every shared position has been found equal. If one tuple contains all the elements of the other in the same order and then ends, the shorter tuple is less than the longer tuple. The shorter tuple is called a prefix of the longer tuple in this situation.

Worked example

Comparing different lengths

Compare the tuples (2, 5) and (2, 5, 0).

  1. 1
    Shared index 0

    Both tuples contain 2, so the comparison continues.

  2. 2
    Shared index 1

    Both tuples contain 5, so all shared elements are equal.

  3. 3
    End of the shorter tuple

    The first tuple ends while the second tuple still has an element.

Result

(2, 5) is less than (2, 5, 0).

(2, 5)(2, 5, 0)2, 5equal shared elementsShorter tuple lessprefix ends firstsharessharesshorter ends
What happens when all shared positions are equal but one tuple runs out of elements first?
Key point

Do not compare a missing element with the next element of the longer tuple. If all shared elements are equal, the tuple that ends first is less.

Later Values Ignored

A common mistake is to scan every value and decide based on a later value that looks more important or much larger. Python does not calculate an overall size for the tuple. It uses the first position where the tuples differ. Therefore, two tuples can contain very different later elements while still having a comparison result determined by an earlier position.

(0, 1, 2000000)1index 1(0, 3, 4)3index 1First tuple lessfirst differing pairfirst differing pair1 < 3determines result
Why can a very large value in a later position have no effect once an earlier pair of elements differs?
  • Common mistake

    Comparing the largest elements first

    What it looks like
    (0, 1, 2000000) versus (0, 3, 4)
    Why it fails

    Python reaches the unequal values 1 and 3 at index 1 before it would consider index 2.

    Do this instead

    Compare from index 0 toward the right and stop at the first unequal pair.

  • Common mistake

    Continuing after finding an unequal pair

    What it looks like

    Treating the values 2000000 and 4 as part of the same decision

    Why it fails

    The comparison has already been decided by 1 and 3.

    Do this instead

    Record the result at the first difference and ignore later positions.

  • Common mistake

    Assuming equal shared elements make different-length tuples equal

    What it looks like
    (2, 5) versus (2, 5, 0)
    Why it fails

    One tuple is a prefix of the other, so the shorter tuple is less than the longer tuple.

    Do this instead

    After matching all shared positions, check which tuple ends first.

Sorting Several Tuples

Python uses this same element-by-element comparison when sorting a list of tuples. It first orders tuples by their first elements. If two tuples have equal first elements, their second elements determine their relative order. The process continues to later positions only when earlier positions match.

3,1 | 3,0 | 2,5input listFirst elements2 before 3Second elements0 before 12,5 | 3,0 | 3,1sorted listcompare index 0equal first elementscompare index 1place 2,5 first
How does Python arrange several tuples by comparing their first differing positions?
Worked example

Ordering a list of tuples

Determine the sorted order of [(3, 1), (3, 0), (2, 5)].

  1. 1
    Place the tuple beginning with 2

    (2, 5) comes before both tuples beginning with 3 because 2 is less than 3.

  2. 2
    Compare the remaining tuples

    (3, 1) and (3, 0) have equal first elements, so Python compares their second elements.

  3. 3
    Use the second elements

    0 is less than 1, so (3, 0) comes before (3, 1).

Result

[(2, 5), (3, 0), (3, 1)]

Prediction Practice

What do you think happens?

Which tuple is less: (4, 2, 900) or (4, 7, 1)?

  • (4, 2, 900)

  • (4, 7, 1)

  • They are equal

Reveal answer
Answer:

(4, 2, 900)

The values at index 0 are equal. At index 1, 2 is less than 7, so Python stops there and does not use 900 or 1.

EASY

Predict the sorted order of [(1, 9), (1, 2), (0, 8)]. State which index determines each important placement.

Hints
  • Compare the first elements before considering the second elements.
  • For the two tuples beginning with 1, compare their second elements.

Summary

  1. 1
    Python compares tuple elements from left to right.
  2. 2
    The first unequal pair determines the result, and later elements are ignored.
  3. 3
    If all shared elements are equal, the shorter tuple is less than the longer tuple.
  4. 4
    Large later values cannot overturn a result decided at an earlier index.
  5. 5
    Sorting a list of tuples uses the same comparison process.

At a glance

  • Tuple comparison proceeds from the first position toward the last.
  • The comparison stops immediately at the first unequal pair.
  • A tuple that is an equal prefix of a longer tuple is less than that longer tuple.
  • Later values, even very large ones, do not matter after an earlier difference.
  • Python sorts lists of tuples by applying this same lexicographic comparison rule.

Related concepts

More concepts starting with S