Lesson · Core Collections
Sorting & Key Functions
72 min readSorting & Key Functions
Python sorting is stable and key-based. The `key` function model is more important than memorizing sorting tricks because it scales from simple values to complex objects and multi-field ordering.
Learning goals
- Choose between
sorted(students)andstudents.sort()based on whether the original list may change. - Explain how the
keycallable turns each record into a comparable value, and why it runs once per element rather than once per comparison. - Read a tuple key such as
(-s.grade, s.name)and predict the exact order it produces. - Use
operator.itemgetterandoperator.attrgetteras reusable extractors when a lambda would only repeat a field name. - Explain why stability lets a second sort refine the order produced by a first one.
Mental model
The sort never sees the records themselves: each element passes through the key callable once, and the resulting keys decide the order while the original objects travel along unchanged. Stability is the second half of the model; it keeps equal keys in their previous relative order, which is what makes two-stage sorting (sort by a secondary field, then by a primary one) safe.
The key runs once; the keys decide the order
stability keeps equal keys in their input order
Mental model
the same mechanism as a compact list
elements → key callable → keys compared → ordered result
(computed once per element)
sorted(...) returns a new list, input untouched
list.sort() reorders in place, returns None
reverse=True flips the comparison, ties keep input order (stability)Core idea
Python sorting is a pipeline: a key callable transforms each element once, the resulting keys are compared, and the result is either a new list from sorted() or a reordered list from the in-place list.sort(). That model scales from plain numbers to records, tuple keys, and reusable extractors such as itemgetter and attrgetter, and stability completes it by guaranteeing that equal keys keep their original relative order.
sorted() vs list.sort()
This comparison separates sorted() from list.sort() in the context of Sorting & Key Functions. Focus on ownership, mutability, cost, failure behavior, and API intent rather than treating the two choices as interchangeable.
key=
Sorting APIs use key= to transform each element into the value used for ordering. Python computes the key once per element during the sort operation.
reverse=
reverse=True reverses the requested ordering while preserving sort stability. It is usually clearer than negating numeric keys when all fields should reverse together.
Stable sorting
Python's sort is stable: records with equal keys keep their previous relative order. Stability lets you build multi-stage sorts safely.
Tuple keys for multi-field sorting
A tuple key sorts lexicographically by its first element, then its second, and so on. This is a concise way to express primary and secondary sort criteria.
Lambda keys
A short lambda is often an appropriate inline sort key when extracting or transforming one simple field. Use a named function when the key logic needs explanation or reuse.
operator.itemgetter
operator.itemgetter creates a callable that extracts one or more indexes or mapping keys. It can make data-extraction sort keys concise and reusable.
operator.attrgetter
operator.attrgetter creates a callable that retrieves one or more named attributes, including dotted attribute paths. It is a declarative alternative to a simple attribute lambda.
operator.methodcaller
operator.methodcaller creates a callable that invokes a named method with preconfigured arguments. It is useful when a higher-order API expects a function-like object.
Sorting records and objects
Sort objects by supplying keys that represent the domain order, rather than adding a global ordering method unless every use of the type shares that same ordering.
When not to sort
When not to sort is a design question rather than a syntax rule. Use the mental model from this lesson to identify the conditions, tradeoffs, and failure modes that make one choice appropriate.
Walkthrough
sorted(students, key=lambda s: (-s.grade, s.name))builds one tuple per student:Adasorts first at95, then the two 90s are ordered by name, soBenprecedesZoe.sortedreturns a new list and leavesstudentsuntouched; replacing it withstudents.sort(...)would reorder the same list and returnNone.sorted(students, key=attrgetter("name"))uses a named extractor instead of a lambda to read.namefrom each student and print them alphabetically.- Predict before running: the two printed orders, where each student lands after the tuple-key sort, and what changes if Zoe's grade is raised to 95.
Experiments to try
- Add
reverse=Trueto theattrgetter("name")call and confirm the names reverse; then try to reverse the tuple-key sort by negating the name and explain why negation fails for strings. - Call
students.sort(key=attrgetter("name"))on the list itself and print the return value; the list changes in place and the method returnsNone. - Sort only by
gradeand inspect the two students at 90; reorder the input list and rerun to watch their relative order follow the input, which is stability. - Build
pairs = [("Zoe", 90), ("Ada", 95), ("Ben", 90)]and comparekey=itemgetter(1, 0)withkey=lambda p: (p[1], p[0]); both produce the same key tuples with different amounts of ceremony.
Playable lesson
Lab: Sorting lab
Let the learner choose primary and secondary key functions and toggle reverse ordering. Preserve original positions to make sort stability visible.
The lab should ask for a prediction before each state transition. Include a reset action and at least one intentionally misleading case.
Sorting lab
key runs once per element; ties keep input order| # | computed key | record | output order |
|---|---|---|---|
| 0 | (-90, Zoe) | Zoe 90 | 1. Ada |
| 1 | (-95, Ada) | Ada 95 | 2. Ben |
| 2 | (-90, Ben) | Ben 90 | 3. Zoe |
sorted(students, key=lambda s: (-s.grade, s.name)) → [Ada, Ben, Zoe]
Ties come out in input order (Zoe before Ben) in both directions, because equal keys never reorder.
Predict first
Sorting by grade only, two students both have 90. What decides their order?
Predict first
`reverse=True` with two equal grades: what happens to those two ties?
Predict first
What does `students.sort(...)` return?
Common mistakes
- Writing
students = students.sort(): the method reorders the list in place and returnsNone, so the name is silently lost;sorted()is the form that returns the list. - Passing the key function positionally:
sorted(students, lambda s: s.name)raisesTypeErrorbecausekeyandreverseare keyword-only. - Assuming
reverse=Truereverses ties too: it flips the comparison, but stability still keeps equal-key records in input order. - Producing keys of mixed or missing types: if one record yields
Noneand another a string, the comparison raisesTypeError; give every record a key of the same comparable type.
Practice: Easy
- Print
sorted(students)with no key and read theTypeErrorabout comparingStudentinstances, then fix it withkey=attrgetter("name"). - Call
students.sort(key=attrgetter("name")), print the list and the return value, and state what the method changed and what it returned. - Sort
[3, 1, 2]once withreverse=Trueand once withkey=lambda n: -n; confirm both print[3, 2, 1]and say which form still works when the elements are strings.
Practice: Medium
- Give two students the same grade, sort with
key=lambda s: (-s.grade, s.name), then swap the tie-break parts of the tuple and explain the output change with the tuple ordering rule. - Sort the
pairslist withitemgetter(1, 0)and with an equivalent lambda; then rewrite the call withattrgetterfor the dataclass version and note when each extractor is the right one. - Run a two-stage sort: first sort the students by name, then sort the result by grade; show that the final order uses name as the tie-break and explain what stability contributed.
Practice: Hard
- Design a sorted report over
Studentrecords: order by grade descending, name ascending, and original position as the final tie-break. Define the key, the tie-break behavior, and one test before implementing. - Build a failure lab with three cases:
students = students.sort(), a positional key argument, and a key that returnsNonefor one record; read each error and explain the mechanism. - Connect this lesson to the complexity lesson: explain why
key=computes each element's key once instead of inside every comparison, and describe a concrete case where a slow key function makes that difference visible.
Lesson checklist
- I can explain how
key=computes one key per element and how the comparison uses those keys. - I can choose between
sorted()andlist.sort()from whether the original list may change. - I can read a tuple key like
(-s.grade, s.name)and state the resulting order before running it. - I can use stability to make a two-stage sort behave as a multi-field sort.
Remember
Python sorting is stable and key-based: the `key` callable turns each element into the value that will be compared, and `sorted()` returns a new list while `list.sort()` reorders in place and returns `None`. Tuple keys and the `operator` extractors cover most record-sorting needs, and stability means equal keys keep their input order, which is what makes multi-stage sorting work.
Interview angles
What is the main purpose of **sorted() vs list.sort()**?+
This comparison separates sorted() from list.sort() in the context of Sorting & Key Functions. Focus on ownership, mutability, cost, failure behavior, and API intent rather than treating the two choices as interchangeable.
What should you pay attention to when using **key=**?+
Sorting APIs use key= to transform each element into the value used for ordering. Python computes the key once per element during the sort operation.
How does **reverse=** fit into this lesson?+
reverse=True reverses the requested ordering while preserving sort stability. It is usually clearer than negating numeric keys when all fields should reverse together.
Why does `sorted(students, lambda s: s.name)` raise, and what is the fix?+
sorted accepts one positional argument; key and reverse are keyword-only, so the lambda lands as an unexpected second positional argument and the call raises TypeError. The fix is sorted(students, key=lambda s: s.name).