Skip to main content
PProfileMatch
← Path

Sorting Algorithms · Python sorted() and Timsort: Stability and Multi-Key Sorting

0 XP
  1. 1 current stop: learning
  2. 2 upcoming
  3. 3 upcoming
  4. 4 upcoming
  5. 5 upcoming

Finish after stop 5

Stop 1 of 5 · Bike shop: sorting by wheel size

Trick to keep in mind+3 XP

Python's sorted() is guaranteed stable: ties keep input order.

Stable means that two items with equal keys stay in the same relative order as they were given. Sorting ["bb", "a", "cc", "d"] by length gives a, d, bb, cc: a before d and bb before cc, because that is how each tie began. The Python docs promise this, so you can build on it.

words = ["bb", "a", "cc", "d"]
print(sorted(words, key=len))   # ['a', 'd', 'bb', 'cc']

Read it once, then a question tests whether the trick stuck.