Skip to content

Stable sorting and keys

Choosing a sort · Article 6 of 8 · 2 min read

Sort records by more than one field without writing a new algorithm.

The short version

A stable sort keeps equal items in their original order. That lets you sort by one field, then sort again by another, and keep the first ordering inside ties.

Details

A key function tells Python what to compare. Python calls it once per item, so it is cheap even for complex records.

Try it yourself

people = [("Ana", 30), ("Ben", 25), ("Cy", 30), ("Di", 25)]
by_name = sorted(people, key=lambda p: p[0])
by_age = sorted(by_name, key=lambda p: p[1])
print(by_age)

You should see [('Ben', 25), ('Di', 25), ('Ana', 30), ('Cy', 30)]. Names stay in order inside each age.

Explain it to the duck

Why would this two step sort give the wrong answer with an unstable algorithm?

Tested with: Python 3.13.