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.
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
- Decorate: call the key function once on every item (no key means the item itself is compared).
- Compare keys with Python's rules: ints by value, strs by code point ('Z' < 'a'), tuples item by item.
- Order the items by key; reverse=True puts the largest key first.
- Stable: items with equal keys keep their original relative order, also with reverse=True.
- 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.
Loading the simulation…
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
- Walk both tuples from index 0 while the items are equal.
- At the first difference, that pair alone decides (later items are never looked at); strs compare by code point.
- If one tuple runs out first, the shorter one is smaller; ordering an int against a str raises TypeError.
- Unpacking checks the count first: too many or too few values raise ValueError before any name is bound.
- 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).
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.
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.
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?
- 1Compare position 0
Both tuples contain 4 at their first position, so this position does not decide the comparison.
- 2Compare position 1
The next values are 2 and 7. Because they differ, the comparison is decided here.
- 3Stop
The final values, 90 and 1, are not considered for this comparison because an earlier difference has already been found.
(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.
| Tuple position | Role in sorting | When it is examined |
|---|---|---|
| First | Primary criterion | Always examined first |
| Second | First tie-breaker | Examined when the first values are equal |
| Later positions | Additional tie-breakers | Examined 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?
Reveal 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.
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.
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.
- 1Decorate
Pair each original record with its derived tuple key. The key contains the values that determine sorting priority.
- 2Sort
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.
- 3Undecorate
After the decorated pairs have been ordered, remove the tuple keys and retain the original records in that new order.
The original records appear in the order associated with keys (1, 9), (2, 1), and (2, 5).
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 likeComparing (1, 9) and (2, 0) by focusing on the second values first
Why it failsTuple comparison starts at the leftmost element. The first values already differ, so the second values cannot change the result.
Do this insteadCompare 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 likeUsing the second value to reorder (1, 8) and (2, 3)
Why it failsThe first values, 1 and 2, already decide the order.
Do this insteadInspect a later position only after all earlier positions are equal.
Common mistake Assuming reverse=True reverses only the primary criterion
What it looks likeExpecting the first tuple element to reverse while later tie-breakers keep their original direction
Why it failsThe source states that reverse=True reverses comparison for all elements in a tuple.
Do this insteadUse a custom key function when different criteria need different directions.
Common mistake Forgetting the undecorate stage in DSU
What it looks likeReturning the sorted decorated pairs when the required result is the original records
Why it failsDSU ends by extracting the original values from the sorted pairs.
Do this insteadAfter sorting, remove the derived tuple keys and keep the original records.
Practice the Trace
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.
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
- 1Tuple comparison proceeds from the first element toward the last.
- 2The first unequal pair decides the comparison, so later elements are ignored for that comparison.
- 3Tuple sort keys express multiple criteria by placing the primary criterion first and tie-breakers later.
- 4The DSU pattern decorates original values with tuple keys, sorts the decorated values, and then extracts the original values.
- 5reverse=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.