sorted() with key=

Sorting by a computed value rather than the item itself, and the difference between sorted() and .sort().

Overview

key is a function of one item

sorted(words, key=len)

key is called once per item and returns the value to sort on. Here len turns each word into its length, and the words come back shortest first. The items in the result are still the words; only the comparison changed.

Anything callable works: a builtin, a lambda, a named function.

sorted(people, key=lambda p: p[1])    # by the second element
sorted(rows, key=lambda r: r["score"])  # by a dict field

sorted_key.py

sorted_key.py Python 3
Output

                    

sorted_vs_sort.py

sorted_vs_sort.py Python 3
Output

                    

Worth knowing

key is a function of one item that returns the value to sort on.
sorted() returns a new list; .sort() rearranges in place and returns None.
Return a tuple from key to sort by one field then another.
The sort is stable, so equal keys keep the order they came in.

sorted() with key=: A Practical Guide

sorted arranges items by comparing them. key= lets you say what to compare instead — a length, a field, a computed score — without touching the items themselves.

Tuple keys give you tiebreaks

Return a tuple and Python compares the first element, then the second where the first ties:

sorted(data, key=lambda t: (t[1], t[0]))

"By count, then alphabetically" in one expression. Negate a number to reverse just that field: (-count, name) sorts by count descending and name ascending, which reverse=True cannot express because it flips everything.

sorted() versus .sort()

new = sorted(nums)  # a new list, original untouched
nums.sort()         # rearranges in place, returns None

The trap is writing nums = nums.sort(), which assigns None and destroys the list. It is a common enough mistake that recognising it is worth more than the rule: if a sort produced None, this is why.

.sort() exists only on lists. sorted() accepts any iterable — a tuple, a string, a set, a dict (giving its keys) — and always hands back a list.

Stability, and why it matters

Python's sort is stable: items that compare equal keep their original relative order. That is what makes multi-pass sorting work. Sort by name, then sort the result by score, and entries with the same score are still in name order. The page shows this directly, sorting only by the number and pointing out that the tied items did not shuffle.

The performance note

key is called exactly once per item, not on every comparison, so an expensive key function is affordable. Doing the same work inside a comparison would cost far more.

Check yourself

0 of 3

Answer without scrolling back up.

  1. What does `nums = nums.sort()` leave in nums?

  2. How do you sort by count descending, then name ascending?

  3. What does a stable sort guarantee?

Cheat sheet

sorted() with key=

sorted arranges items by comparing them. key= lets you say what to compare instead — a length, a field, a computed score — without touching the items themselves.

PYTHON · vizlearn.in/python/sorted_with_key.html

About the author

Ashish Jangra builds and maintains VizLearn. Every module here is written and the visualisation behind it hand-built, so the numbers in a readout come from the same code that draws the picture. Corrections are genuinely welcome and get priority over everything else — if a page states something wrong, or an animation misrepresents what the algorithm does, get in touch.