Sorting Lists and Other Sequences
When a sequence contains tuples, sorting begins with the first element of each tuple.
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…
The First Comparison
When a sequence contains tuples, sorting begins with the first element of each tuple. The comparison moves to the next element only if the values already compared are tied. This gives tuple sorting a predictable, left-to-right ordering.
Tie-Breaking Positions
The first tuple element is the primary sorting criterion. If two tuples have the same first element, sorting compares their second elements. If those are also equal, it compares the third elements, continuing in order as needed. This is lexicographic ordering: the position of a value inside the tuple determines when that value participates in the decision.
Student Records with a Shared Name
Consider tuples representing student records in the order (name, score, year). How does sorting decide between two records whose names are equal?
- 1Primary comparison
Sorting first compares the names, because name is the first tuple element.
- 2First tie
If two records have the same name, sorting compares their scores, the second tuple element.
- 3Second tie
If the name and score are both equal, sorting compares the year, the third tuple element.
The tuple is designed so that name has priority, score breaks a name tie, and year breaks a tie between records with the same name and score.
Choosing Tuple Order
Place the most important sorting criterion first in each tuple. Sorting gives the first position priority, so the tuple layout determines which characteristic is considered before the others. In a student record, placing the name first makes name the primary criterion, while score and year act as tie-breakers.
Reversing Every Comparison
The keyword argument reverse=True changes the tuple sort to decreasing order. The reversal applies to the entire comparison logic: values later in the first element come earlier, and within a group sharing that first element, later values in the next element also come earlier.
For the student-record example, using reverse=True places names later in the alphabet first. The source gives the resulting order as ('Charlie', 85), ('Bob', 90), ('Alice', 90), ('Alice', 85). The two Alice tuples are then ordered by score in decreasing order, so 90 comes before 85.
Predicting the Final Sequence
What do you think happens?
Suppose tuples are ordered by name first and score second. With reverse=True, which sequence comes first: ('Alice', 85), ('Alice', 90), ('Bob', 90), ('Charlie', 85), or the reverse order shown in the source example?
Reveal answer
('Charlie', 85), ('Bob', 90), ('Alice', 90), ('Alice', 85)
reverse=True makes the first elements decrease from later names to earlier names. Within the two Alice tuples, the equal first elements create a tie, so the scores are compared and 90 comes before 85.
Explain why a tuple with a later first element can appear before a tuple with an earlier first element when reverse=True is used. Then identify which tuple position resolves the order when the first elements are equal.
Hints
- Start with the first tuple element.
- Remember that reverse=True reverses the comparison at every level.
- Move to the next position only after finding a tie.
Common Sorting Mistakes
Common mistake Assuming every tuple element has equal priority.
What it looks likeTreating the score as more important than the name even though the tuple places name first.
Why it failsSorting starts with the first position and reaches later positions only when earlier values tie.
Do this insteadPlace the most important criterion in the first tuple position.
Common mistake Using the second element when the first elements are different.
What it looks likeComparing scores between ('Alice', 90) and ('Bob', 85) before comparing their names.
Why it failsThe first elements already determine the ordering, so the scores are not needed for that comparison.
Do this insteadCompare tuple positions from left to right and move right only after a tie.
Common mistake Reversing only the first element's order mentally.
What it looks likeExpecting the names to decrease but the scores within an equal-name group to increase.
Why it failsreverse=True reverses the entire comparison logic, including tie-breaking levels.
Do this insteadApply decreasing order to the first element and to each later element used to break a tie.
Key Takeaways
- Tuple sorting compares elements from the first position toward later positions.
- A later element is used only when all earlier compared elements are tied.
- The tuple's position order determines the priority of sorting criteria.
- reverse=True sorts in decreasing order at every comparison level.
- To predict a result, compare the first elements first, then use later elements only for ties.