Concepts / Sorting Lists and Other Sequences

Sorting Lists and Other Sequences

When a sequence contains tuples, sorting begins with the first element of each tuple.

  • 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…

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.

(Alice, 90)student recordAlicefirst element90second element(Bob, 90)student recordBobfirst element90second elementcompare firstcompare firstAlice comes before Bobnot needednot needed
How does sorting decide which tuple comes first when it compares tuple positions from left to right?

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.

Compare firstelementsDifferent valuesFirst positiondecidesContinue if tiedEqual valuesCompare next elementscomparisonno tietiemove righttie again
What happens next when two tuples have equal values in their first element?
Worked example

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?

  1. 1
    Primary comparison

    Sorting first compares the names, because name is the first tuple element.

  2. 2
    First tie

    If two records have the same name, sorting compares their scores, the second tuple element.

  3. 3
    Second tie

    If the name and score are both equal, sorting compares the year, the third tuple element.

Result

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

Best practice

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.

Increasing orderAlice, Bob, CharlieDecreasing orderCharlie, Bob, Alicesorted resultreverse=True
What changes in the final ordering when reverse=True is applied to a tuple sort?
In the real world

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?

  • ('Alice', 85), ('Alice', 90), ('Bob', 90), ('Charlie', 85)

  • ('Charlie', 85), ('Bob', 90), ('Alice', 90), ('Alice', 85)

Reveal answer
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.

Original sequenceAlice 85; Charlie 85;Alice 90; Bob 90Sorted withreverse=TrueCharlie 85; Bob 90;Alice 90; Alice 85given ordercompare positionsresult
How do the original tuple sequence and the sorted sequence differ after primary and tie-breaking comparisons?
MEDIUM

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 like

    Treating the score as more important than the name even though the tuple places name first.

    Why it fails

    Sorting starts with the first position and reaches later positions only when earlier values tie.

    Do this instead

    Place the most important criterion in the first tuple position.

  • Common mistake

    Using the second element when the first elements are different.

    What it looks like

    Comparing scores between ('Alice', 90) and ('Bob', 85) before comparing their names.

    Why it fails

    The first elements already determine the ordering, so the scores are not needed for that comparison.

    Do this instead

    Compare 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 like

    Expecting the names to decrease but the scores within an equal-name group to increase.

    Why it fails

    reverse=True reverses the entire comparison logic, including tie-breaking levels.

    Do this instead

    Apply 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.

Related concepts

More concepts starting with S