Order Values Predictably
Return an ordered list without changing its source, then make value-first ordering and label tie-breaking explicit through a named key.
Measurements often arrive in collection order but need a different order for comparison or display. Python can return an ordered result while preserving the source sequence.
sorted Returns a New List
sorted(readings) returns a new list. It does not change readings. This is
useful when both arrival order and numerical order matter.
A list's .sort() method behaves differently:
readings.sort()
It changes the existing list and returns None. Do not write
readings = readings.sort(), because that replaces the list reference with
None.
Use reverse=True when descending order is the actual requirement:
highest_first = sorted(readings, reverse=True)
Q1. Keep the source order
After this code runs, what are ordered and readings?
Select one choice, then check.
HintFollow the returned value
sorted returns a new list; this code never calls readings.sort().
SolutionThe two orders remain available
ordered receives [1, 2, 3], while readings keeps [3, 1, 2].
Name the Value Used for Ordering
Labelled readings can be represented as small pairs:
To order by reading and then by label, define a key function:
Python calls the key function for each report. The returned pair supplies the order: compare the reading first; if readings tie, compare the label. The result is:
The key names the rule. It does not change the report.
Q2. Read a named sort key
What key does reading_then_label(("sensor-b", 20)) return?
Select one choice, then check.
HintRead the return expression
The function returns reading, label.
SolutionThe key reverses the input roles
The report unpacks to label = "sensor-b" and reading = 20, then the key
returns (20, "sensor-b").
Read the Equivalent Small lambda
You may see the same simple rule written without a separate function:
ordered = sorted(reports, key=lambda report: (report[1], report[0]))
Read lambda report: ... as a small unnamed function with one parameter and
one returned expression. Here it returns the reading at index 1 and the label
at index 0. The named function is clearer when the rule needs explanation,
testing, or reuse.
Q3. Order labelled readings
Complete the named key so the program orders by reading and then label without
changing reports.
Editable Python
Ready to run.
HintReturn the comparison order
Use return reading, label, then assign
ordered = sorted(reports, key=reading_then_label).
SolutionUse a named two-part key
sorted can produce a predictable order without changing the source. A
named key makes the comparison rule visible, including tie-breaking. The
next chapter uses meaningful keys for lookup and counting, then examines
uniqueness and shared or copied collections.