Hone

Lessons · Python · stable sorting

Sort by two things

Python's sort is stable: items that compare equal keep their original order. Sort by the secondary key first, then by the primary, and ties stay ordered.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

By department, then by name inside each department; by date, then by time: two-level ordering is most reports, and stability makes it two lines instead of a custom comparison.

How to think about it

Either sort twice, least important key first, or sort once with a tuple key: key=lambda r: (r['dept'], r['name']). Tuples compare element by element.

Worked example

people = [("Bo", "ops"), ("Ada", "eng"), ("Cy", "ops"), ("Al", "eng")]
Name and department.
people.sort(key=lambda p: p[0])
By name first.
people.sort(key=lambda p: p[1])
Then by department; equal departments keep the name order.
print(people)
[('Ada', 'eng'), ('Al', 'eng'), ('Bo', 'ops'), ('Cy', 'ops')].
print(sorted(people, key=lambda p: (p[1], p[0])))
The same result with one tuple key.

Your turn

Oldest first, and alphabetical within the same age.

rows.sort(key=lambda r: (r["age"], r[""]))

The trap

Sorting by the primary key first and the secondary second gives the wrong order: the second sort scrambles the first. Least important first.

Practise stable sorting on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.