Concepts / Understanding Tuples as Immutable Sequences

Understanding Tuples as Immutable Sequences

Read a tuple from left to right when reasoning about its order. The first unequal pair decides the comparison, so later elements matter only when earlier elements are equal.

  • Programming
Interactive lab

Try it: Sorting with key= and reverse=

How sorted() and list.sort() compute key(item) once per item, order the items by those keys with Python's comparison rules, and keep equal keys in their original order — including py4e's sort-a-dict-by-value pattern.

How it works

  1. Decorate: call the key function once on every item (no key means the item itself is compared).
  2. Compare keys with Python's rules: ints by value, strs by code point ('Z' < 'a'), tuples item by item.
  3. Order the items by key; reverse=True puts the largest key first.
  4. Stable: items with equal keys keep their original relative order, also with reverse=True.
  5. sorted() returns a new list; list.sort() rearranges the list in place and returns None; [:N] keeps the first N.

Default run (12 steps): 5 items in their original order. Python will call lambda t: t[1] once per item. … sorted() returned a new list: result = [('fig', 5), ('kiwi', 5), ('pear', 3), ('apple', 3), ('date', 1)].

Simplified: Up to 10 items of one kind (ints, short ASCII words, (word, count) tuples or a small dict) and a fixed menu of key functions. The sorting algorithm itself (Timsort) is not shown — only what it guarantees: the order by key and stability.

Educational simulation

Loading the simulation…

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…

Why Tuple Order Matters

A tuple can act as more than a grouped collection of values. When tuples are compared, Python examines their elements from left to right. This makes the position of each element meaningful: an earlier element can decide the comparison before later elements are considered. The same rule makes tuples useful as sorting keys for several criteria.

Key point

Read a tuple from left to right when reasoning about its order. The first unequal pair decides the comparison, so later elements matter only when earlier elements are equal.

The Left-to-Right Comparison

To compare two tuples, begin with their first elements. If those elements differ, the comparison is decided immediately. If they are equal, move to the second elements and repeat the same process. Continue in this way only until the first difference appears. Any elements after that difference do not influence that comparison.

4position 04position 02position 17position 190position 21position 2equal; continue2 differs from 7; decide
How does Python compare two tuples element by element, and what happens after it finds the first unequal pair?
Worked example

Finding the Deciding Pair

Compare the tuple keys (4, 2, 90) and (4, 7, 1). Which key comes first when the tuples are ordered from smaller to larger?

  1. 1
    Compare position 0

    Both tuples contain 4 at their first position, so this position does not decide the comparison.

  2. 2
    Compare position 1

    The next values are 2 and 7. Because they differ, the comparison is decided here.

  3. 3
    Stop

    The final values, 90 and 1, are not considered for this comparison because an earlier difference has already been found.

Result

(4, 2, 90) comes before (4, 7, 1) because 2 is smaller than 7 at the first position where the tuples differ.

Tuple Keys for Multiple Criteria

A tuple sort key expresses priority by position. Put the primary criterion first. Put the next criterion second so it can break ties among records with equal primary values. Continue adding criteria in priority order. Because tuple comparison proceeds from left to right, this arrangement naturally gives earlier criteria greater influence.

(2, 4)primary 2; secondary 4Primary valuefirst tuple element(2, 9)primary 2; secondary 9Secondary valuelater tuple elementcompare firstcompare firstif tied
How does a tuple sort key use the first attribute as the primary criterion and later attributes to break ties?
Tuple positionRole in sortingWhen it is examined
FirstPrimary criterionAlways examined first
SecondFirst tie-breakerExamined when the first values are equal
Later positionsAdditional tie-breakersExamined only when all earlier values are equal

The position of a value in a tuple determines its priority during comparison.

Predicting a Sorted Result

What do you think happens?

These tuple keys are sorted from smaller to larger: (1, 8), (1, 3), (2, 0). Which order should they have after sorting?

  • (1, 3), (1, 8), (2, 0)

  • (2, 0), (1, 3), (1, 8)

  • (1, 8), (1, 3), (2, 0)

Reveal answer
Answer:

(1, 3), (1, 8), (2, 0)

The first values are compared first. Both keys beginning with 1 come before the key beginning with 2. Between (1, 3) and (1, 8), the first values tie, so the second values decide: 3 comes before 8.

Tuple keys(1, 8), (1, 3), (2, 0)Compare firstelements1, 1, 2Compare secondelementsfor the keys beginning with1Sorted keys(1, 3), (1, 8), (2, 0)startequal first values2 follows both 1 values3 before 8
What final order results when a collection of records is sorted by comparing their tuple keys?

To predict a sorted result, do not compare every field at once. First group or order the keys by their first element. Then resolve only the ties by inspecting the next element. This method follows the same stopping rule used in a direct tuple comparison.

Following the DSU Pattern

The Decorate-Sort-Undecorate pattern, abbreviated DSU, uses tuples to sort original values by derived criteria. First, decorate each original value by pairing it with a tuple containing the desired sort keys. Next, sort the decorated values. Finally, undecorate them by extracting the original values from the sorted pairs. The tuple comparison rule controls the middle stage.

Original recordsrecord A, record B, recordCDecorated pairs(tuple key, record)Sorted pairstuple comparison decidesorderSorted recordsoriginal records restoreddecorate with sort keyssort tuplesextract original values
How does data move from the original records to derived tuple keys, through sorting, and back to the original records?
Worked example

Tracing a DSU Sort

Suppose three records are assigned tuple keys (2, 5), (1, 9), and (2, 1). Trace how DSU orders the original records.

  1. 1
    Decorate

    Pair each original record with its derived tuple key. The key contains the values that determine sorting priority.

  2. 2
    Sort

    Compare the tuple keys from left to right. The key beginning with 1 comes before both keys beginning with 2. Between the two keys beginning with 2, compare their second values: 1 comes before 5.

  3. 3
    Undecorate

    After the decorated pairs have been ordered, remove the tuple keys and retain the original records in that new order.

Result

The original records appear in the order associated with keys (1, 9), (2, 1), and (2, 5).

Key point

DSU separates what is being sorted from how it is ranked. The original record is carried through the process, while the tuple supplies the comparison values.

Mistakes in Tuple Sorting

  • Common mistake

    Treating every tuple element as equally important from the beginning

    What it looks like

    Comparing (1, 9) and (2, 0) by focusing on the second values first

    Why it fails

    Tuple comparison starts at the leftmost element. The first values already differ, so the second values cannot change the result.

    Do this instead

    Compare positions in order and stop at the first unequal pair.

  • Common mistake

    Using a later value to break a tie when an earlier value is not tied

    What it looks like

    Using the second value to reorder (1, 8) and (2, 3)

    Why it fails

    The first values, 1 and 2, already decide the order.

    Do this instead

    Inspect a later position only after all earlier positions are equal.

  • Common mistake

    Assuming reverse=True reverses only the primary criterion

    What it looks like

    Expecting the first tuple element to reverse while later tie-breakers keep their original direction

    Why it fails

    The source states that reverse=True reverses comparison for all elements in a tuple.

    Do this instead

    Use a custom key function when different criteria need different directions.

  • Common mistake

    Forgetting the undecorate stage in DSU

    What it looks like

    Returning the sorted decorated pairs when the required result is the original records

    Why it fails

    DSU ends by extracting the original values from the sorted pairs.

    Do this instead

    After sorting, remove the derived tuple keys and keep the original records.

Practice the Trace

MEDIUM

Predict the sorted order of these tuple keys from smaller to larger: (3, 2), (1, 8), (3, 1), (2, 6). Explain which position decides each step and identify the tie that requires a second-element comparison.

Hints
  • Start by ordering the first elements: 1, 2, and 3.
  • The two keys beginning with 3 are tied at their first position.
  • Compare the second values of the tied keys to place them correctly.
MEDIUM

Describe the DSU stages for a collection of records that must be ordered by two derived attributes. State what is created during decoration, what determines the order during sorting, and what is removed during undecoration.

Hints
  • Decoration attaches a tuple of sort keys to each original record.
  • Sorting compares those tuples from left to right.
  • Undecoration extracts the original records after the pairs have been ordered.

Working Rules

  1. 1
    Tuple comparison proceeds from the first element toward the last.
  2. 2
    The first unequal pair decides the comparison, so later elements are ignored for that comparison.
  3. 3
    Tuple sort keys express multiple criteria by placing the primary criterion first and tie-breakers later.
  4. 4
    The DSU pattern decorates original values with tuple keys, sorts the decorated values, and then extracts the original values.
  5. 5
    reverse=True reverses comparison for every tuple element; use a custom key function for finer control over different sorting directions.

Key Takeaways

  • Python compares tuple elements from left to right and stops at the first difference.
  • The first tuple element acts as the primary sort criterion; later elements resolve ties.
  • Sorting records by tuple keys lets one comparison represent several ordering criteria.
  • DSU moves from original records to decorated tuple-key pairs, sorts those pairs, and extracts the original records.
  • reverse=True affects every element of a tuple, so a custom key function is preferable when criteria need different directions.

More concepts starting with U