Concepts / Sorting Lists with the sort() Method

Sorting Lists with the sort() Method

The position of a value inside the tuple expresses its sorting priority. Moving a criterion earlier makes it more influential because it can decide the comparison before later criteria are considered.

  • 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 Difference Decides

A tuple can carry several sorting criteria in a fixed order. Python compares the first elements of two tuples first. If those elements differ, that difference determines the ordering. Python does not need to use later elements. It examines the next element only when the earlier elements are equal.

2first element5first element9not inspected1not inspected4not inspected8not inspectedif equalif equal
Which tuple elements does Python inspect, and where does the comparison stop?

A Comparison Trace

What do you think happens?

Which tuple comes first when Python compares (2, 9, 4) with (5, 1, 8)?

  • (2, 9, 4)

  • (5, 1, 8)

  • They cannot be ordered

Reveal answer
Answer:

(2, 9, 4)

The first elements differ: 2 is less than 5. That first difference decides the comparison, so the later elements are not needed.

Worked example

Comparing Two Candidate Keys

Determine the order of (3, 7) and (3, 2).

  1. 1
    Compare the first elements

    Both first elements are 3, so the first position does not decide the ordering.

  2. 2
    Move to the next position

    Compare 7 with 2. Because 2 is less than 7, (3, 2) comes before (3, 7).

  3. 3
    Stop at the first difference

    The second elements differ, so there is no need to inspect any later position.

Result

(3, 2) comes before (3, 7).

This comparison rule gives a sorted list a predictable priority structure. The first tuple element is the primary criterion. The second element is a tie-breaker used only when the primary criteria match. Additional elements continue the same pattern.

Tuple Keys for Multiple Criteria

To sort records by more than one attribute, represent each record with a tuple of sort keys. Put the most important criterion first, followed by the tie-breaking criteria. Sorting then applies the tuple comparison rule: compare the primary key first, and consult the next key only when the earlier key is equal.

Aprimary 1, secondary 8(1, 8)sort keyBprimary 1, secondary 3(1, 3)sort keyCprimary 2, secondary 1(2, 1)sort keymaps tomaps tomaps to
How does a tuple sort key order items first by one attribute and then by the next?
Worked example

Sorting by Priority and Name

Three items have sort keys: Alpha has (1, 8), Beta has (1, 3), and Gamma has (2, 1). Predict their order when the tuple keys are sorted.

  1. 1
    Compare the primary values

    Alpha and Beta both have primary value 1. Gamma has primary value 2, so both Alpha and Beta come before Gamma.

  2. 2
    Break the tie

    Alpha and Beta have equal primary values, so compare their second values: 3 comes before 8.

  3. 3
    Assemble the result

    The tuple keys therefore appear in the order (1, 3), (1, 8), and (2, 1).

Result

Beta, Alpha, Gamma

Key point

The position of a value inside the tuple expresses its sorting priority. Moving a criterion earlier makes it more influential because it can decide the comparison before later criteria are considered.

Reading a Sorted Result

(1, 4)first(1, 4)(1, 9)second(1, 9)(2, 0)third(2, 0)ordered asordered asordered as
What order results when each pair is resolved by the first differing tuple element?

When predicting a sorted result, do not compare all tuple elements at once. For each pair, begin at the leftmost position. If the values differ, record the ordering immediately. If they match, move right and repeat. This prevents a later, smaller value from incorrectly overriding an earlier difference.

Worked example

A Three-Item Trace

Order the keys (2, 5), (1, 9), and (2, 1).

  1. 1
    Place the key beginning with 1

    The first element 1 is less than 2, so (1, 9) comes before both keys beginning with 2.

  2. 2
    Compare the tied primary values

    The remaining keys both begin with 2, so compare their second elements: 1 is less than 5.

  3. 3
    Write the complete order

    The keys are ordered as (1, 9), (2, 1), and (2, 5).

Result

(1, 9), (2, 1), (2, 5)

The DSU Sorting Pipeline

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 one or more sort keys. Next, sort the decorated tuples. Finally, undecorate the result by extracting the original values from the sorted tuples.

original valuessort key + valueordered tuplesoriginal valuesdecoratesort tuplesextract values
How does each original item become a decorated item with a derived sort key, move through sorting, and return to its original form?
Worked example

Tracing a Derived Sort Key

Sort the original values Cedar, Oak, and Ash by their name lengths using the DSU pattern.

  1. 1
    Decorate

    Pair each value with its derived key: Cedar becomes (5, Cedar), Oak becomes (3, Oak), and Ash becomes (3, Ash).

  2. 2
    Sort

    Compare the tuple keys from left to right. The tuples beginning with 3 come before the tuple beginning with 5. Between (3, Oak) and (3, Ash), the first elements tie, so the second elements decide their order.

  3. 3
    Undecorate

    After the decorated tuples have been ordered, remove the derived keys and keep the original values.

Result

Ash, Oak, Cedar

Key point

DSU separates the work into three understandable stages: create comparison-friendly tuples, sort those tuples, and recover the original values. The tuple comparison rule controls the middle stage.

Reverse Ordering Choices

The reverse=True option reverses the comparison for all elements in a tuple. Therefore, it affects both the primary criterion and the tie-breaking criteria. It is not a way to reverse only one selected position in a multi-criteria tuple.

ApproachEffect on tuple criteriaBest interpretation
Tuple sort keyEarlier elements have priority; later elements break tiesUse for ordered multi-criteria keys
reverse=TrueReverses comparison for all tuple elementsUse when every tuple criterion should reverse together
Custom key functionProvides finer-grained control over multi-criteria sortingUse when criteria require different ordering directions

How tuple keys and reverse ordering differ

Mistakes in Tuple Sorting

  • Common mistake

    Looking at the second tuple element before checking the first

    What it looks like

    Treating (1, 9) as greater than (2, 0) because 9 is greater than 0

    Why it fails

    The first elements differ, and 1 is less than 2. That first difference decides the ordering.

    Do this instead

    Compare tuple positions from left to right and stop when the first difference appears.

  • Common mistake

    Using a later criterion as if it were the primary criterion

    What it looks like

    Trying to order records by the second value even though the first value was intended to be the main grouping

    Why it fails

    Tuple position determines priority.

    Do this instead

    Place the most important sort key first and use later positions for tie-breaking.

  • Common mistake

    Assuming reverse=True reverses only the primary criterion

    What it looks like

    Expecting the first tuple element to reverse while the second element keeps its original direction

    Why it fails

    reverse=True reverses the comparison for all elements in the tuple.

    Do this instead

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

  • Common mistake

    Skipping the undecorate stage in DSU

    What it looks like

    Returning the sorted tuples when the desired result is the original values

    Why it fails

    DSU uses tuples during sorting but extracts the original values afterward.

    Do this instead

    After sorting, remove the derived sort keys and retain the original values.

Check Your Reasoning

MEDIUM

A collection has these tuple keys: (4, 2), (2, 9), (4, 1), and (2, 3). Predict the sorted order. Then identify which comparisons require the second element.

Hints
  • Group the keys by their first element.
  • Within each group sharing a first element, compare the second elements.
  • The second element is needed only when the first elements are equal.
MEDIUM

Design a DSU trace for the original values Pine, Elm, and Birch, using string length as the derived key. Show the decorated tuples, their sorted order, and the final undecorated order.

Hints
  • Create one tuple containing the derived length and the original value for each item.
  • Compare the tuples from left to right.
  • Extract the original value after the decorated tuples are ordered.

Key Takeaways

  1. 1
    Python compares tuples from left to right and stops at the first difference.
  2. 2
    The first tuple element is the primary sort criterion; later elements break ties.
  3. 3
    Tuple keys support multi-criteria sorting by placing criteria in priority order.
  4. 4
    DSU decorates original values with sort keys, sorts the tuples, and then extracts the original values.
  5. 5
    reverse=True reverses every tuple comparison criterion, so a custom key function is preferable for fine-grained control.

At a glance

  • Tuple comparison proceeds left to right and stops at the first differing element.
  • A tuple sort key expresses primary, secondary, and later sorting priorities by position.
  • When earlier tuple elements match, Python uses the next element as a tie-breaker.
  • The DSU pattern sorts derived keys while preserving a path back to the original values.
  • reverse=True reverses all tuple criteria; use a custom key function for more selective control.

More concepts starting with S