Concepts / Tuple Ordering and Lexicographic Comparison

Tuple Ordering and Lexicographic Comparison

Tuple position controls sorting priority. Put the field you want to sort by first.

  • 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 Field Python Sees First

Suppose a dictionary contains pairs such as alpha mapped to 30, beta mapped to 10, and gamma mapped to 20. If those entries remain in their usual key-value form, each pair begins with a key. Sorting those tuples therefore uses the key as the first sorting field. To sort by the values instead, reconstruct each pair so that the value comes first: 30 paired with alpha, 10 paired with beta, and 20 paired with gamma.

Key point

Tuple position controls sorting priority. Put the field you want to sort by first.

Comparing Tuples Left to Right

Tuple ordering is lexicographic: Python compares the first element of one tuple with the first element of the other tuple. If those first elements differ, that comparison determines the order. If they match, comparison proceeds to the next element. This makes the first tuple position the primary sorting field and the second position a later comparison field.

(10, beta)first element: 10First elements10 and 20 differ(20, gamma)first element: 20Second elementsexamined only if firstelements matchcompare first positioncompare first positiononly when equal
When Python compares two tuples, which element does it examine first, and when does it examine the second element?
Worked example

Reading Two Tuples

Determine which tuple comes first when comparing (10, beta) and (20, gamma).

  1. 1
    Compare position one

    The first elements are 10 and 20.

  2. 2
    Stop when they differ

    Because the first elements are different, their order determines the tuple order.

  3. 3
    Use the second position only when needed

    The names beta and gamma do not need to decide this comparison because the first elements already differ.

Result

(10, beta) comes before (20, gamma).

Swapping the Tuple Positions

A dictionary entry naturally appears as a key-value pair. To prepare for value-based sorting, reconstruct that pair in the opposite order. The key remains present, but it moves to the second position. The value moves to the first position, where tuple ordering examines it first.

(alpha, 30)key first(30, alpha)value first(beta, 10)key first(10, beta)value first(gamma, 20)key first(20, gamma)value firstswap positionsswap positionsswap positions
How does each dictionary entry change when it is transformed from key-value order into value-key order, and how does that change select the sorting field?

For the generated example, the reconstructed list is [(30, alpha), (10, beta), (20, gamma)]. A simple sorted operation then compares 30, 10, and 20 first, producing [(10, beta), (20, gamma), (30, alpha)]. The keys are carried along as the second tuple elements, so the association between each value and its key is preserved.

Dictionary entries(key, value)Reconstructed tuples(value, key)Sorted listvalues in first positionswap tuple positionsapply sorted()
How do key-value pairs move into reconstructed tuples and then into a list ordered by value?

Predicting the Final Order

What do you think happens?

The reconstructed tuples are (40, cedar), (15, birch), and (25, maple). Which tuple comes first when they are ordered?

  • (40, cedar)

  • (15, birch)

  • (25, maple)

Reveal answer
Answer:

(15, birch)

The first elements are 40, 15, and 25. Since 15 is the smallest first element, (15, birch) comes first. The second elements are not needed for this comparison.

When first elements are different, sort order is determined entirely by those first elements. If two reconstructed tuples have the same value in the first position, tuple comparison continues to the second position, which contains the key. Thus the value is the primary sorting field, while the key can determine the order among tuples whose first elements match.

Worked example

Using the Second Element After a Tie

Determine the order of (20, zeta) and (20, alpha).

  1. 1
    Compare the first elements

    Both tuples begin with 20, so the first position does not determine the order.

  2. 2
    Compare the second elements

    The second elements are zeta and alpha. Tuple comparison proceeds to this position because the first elements match.

  3. 3
    Place the smaller second element first

    alpha comes before zeta in the second position.

Result

(20, alpha) comes before (20, zeta).

Mistakes with Original Pairs

  • Common mistake

    Passing the original key-value pairs directly to sorted() when the goal is value-based ordering.

    What it looks like

    The pairs remain in the form (key, value).

    Why it fails

    The key occupies the first tuple position, so lexicographic comparison uses the key as the primary sorting field.

    Do this instead

    Reconstruct every pair as (value, key) before applying sorted().

  • Common mistake

    Assuming that calling .items() alone changes the sorting field.

    What it looks like

    The dictionary entries are obtained as key-value pairs and then sorted without swapping their positions.

    Why it fails

    The tuple still begins with the key, so the first comparison remains key-based.

    Do this instead

    Use the entries as input for a transformation that places the value first.

  • Common mistake

    Swapping the positions but then reading the result as though it were still a key-value pair.

    What it looks like

    After reconstruction, (10, beta) is mistakenly interpreted as key 10 with value beta.

    Why it fails

    The reconstructed tuple intentionally has value first and key second.

    Do this instead

    Keep track of the tuple shape: reconstructed pairs are (value, key), and the second element is the original key.

Tuple formFirst comparison fieldSorting result
(key, value)KeyKey-based ordering
(value, key)ValueValue-based ordering

Changing tuple position changes which dictionary field lexicographic ordering examines first.

Practice the Transformation

EASY

A dictionary has the entries oak mapped to 12, pine mapped to 5, and birch mapped to 9. Write the reconstructed tuples in value-key form, then state the order produced by sorting those tuples.

Hints
  • Move each value into the first position.
  • Compare the first elements before comparing any keys.
  • The values to order are 12, 5, and 9.
Worked example

Practice Solution

Order the entries oak mapped to 12, pine mapped to 5, and birch mapped to 9 by value.

  1. 1
    Reconstruct the pairs

    The value-key tuples are (12, oak), (5, pine), and (9, birch).

  2. 2
    Compare the first elements

    The first elements are 12, 5, and 9. Their ascending order is 5, 9, and 12.

  3. 3
    Carry each key with its value

    Each key remains attached as the second element of its tuple.

Result

The sorted order is (5, pine), (9, birch), (12, oak).

The Sorting Pattern

  1. 1
    Tuple comparison examines the first element before later elements.
  2. 2
    Dictionary entries normally have the shape (key, value), so their first sorting field is the key.
  3. 3
    Reconstructing entries as (value, key) places the desired sorting field first.
  4. 4
    After reconstruction, a simple sorted() call produces a value-ordered list while preserving each key with its value.
  5. 5
    If first elements match, lexicographic comparison continues to the second element.

Key Takeaways

  • Python orders tuples lexicographically, examining the first element first.
  • Sorting original key-value pairs produces key-based ordering because the key is first.
  • Reconstructing each entry as a value-key tuple makes the value the primary sorting field.
  • The key remains available as the second element and can resolve comparisons when values match.

More concepts starting with T