~/learn/Python · Algorithms for interviews

Sorting tricks

Custom keys, multi-level sorts and top-K.

8 min readlesson 18 of 23sortedkeyheapq

why this matters

Leaderboards, rankings and 'top 5 by X then Y' questions all come down to writing the right sort key.

sorted returns a new list and .sort() sorts in place. The key function decides what is compared — that is where all the power is.

python · editable
loading editor…

Try it: Sort by revenue (price times units), highest first.

Python's sort is stable, so sorting twice applies a secondary then a primary key — or use a tuple key, negating numbers to flip direction.

When you only need the largest few, heapq beats a full sort at scale.

python · editable
loading editor…

Multi-level sorting

sorted(rows, key=lambda r: (-r["score"], r["name"]))
                        ↑ desc      ↑ then asc

Pro tip

For just the top few from a huge list, heapq.nlargest(5, items) beats sorting everything.

Common gotcha

sorted() returns a new list; list.sort() changes it in place and returns None. Assigning the result of .sort() gives you None.

key takeaways

  • key= controls what you sort by.
  • A tuple key sorts by several fields in order.
  • Negate a number to sort it descending.

check your understanding

Sort by score descending, then name ascending. Which key?

free practice

Build confidence with a question you can solve without Pro.