Free lab Real Python 3. Zero installs. Your code stays in this browser. Open the playground

Sorting: sorted(), Keys & Custom Order

14 min 35 XP
Study loop Read Predict Run Tweak Prove Review
Lesson 3 of 5 · View course roadmap
Step 1

Learn the idea

You'll rarely write a sorting algorithm — Python's sorted() (Timsort, invented for Python, adopted by Java and Android) is world-class. The real skill is telling it what order means:

  • sorted(words) — alphabetical
  • sorted(words, key=len) — by length; the key function is called on each item and the results are compared instead
  • sorted(words, key=lambda w: (len(w), w)) — by length, ties broken alphabetically — tuples compare position by position
  • reverse=True — flip any of the above

The tuple-key trick is the professional move: 'sort by department, then salary descending, then name' is one line in Python.

Where you'll use this

Every table header you've ever clicked runs a key-based sort. Timsort — invented for Python — now also sorts Java and Android. The tuple-key trick handles real reporting: department, then salary, then name.

Common mistakes

  • Confusing sorted(items) (returns a new list) with items.sort() (in place, returns None) — printing the result of .sort() gives None.
  • Sorting strings expecting numeric order: "10" < "9" alphabetically. Convert first or use key=int.
  • Reaching for cmp-style comparison logic — Python only does key functions, which are simpler anyway.

Pro tip

Sort descending on one field and ascending on another by negating numbers: key=lambda r: (-r["score"], r["name"]).

Step 2

Try it yourself

Blank · autosaved

The lesson example is loaded and ready — press Run, then change something and run it again. Breaking it is part of learning. Want a clean slate? Tap “New blank”.

PYexample.py
+ Enter to run
Output appears here…
Step 3

Pass the challenge +35 XP

Blank · autosaved

For words = ["banana", "fig", "cherry", "kiwi", "apple"]: first print them sorted alphabetically, joined by ", ". Then print them sorted by length with alphabetical tie-breaks, joined the same way.

Target output
apple, banana, cherry, fig, kiwi
fig, kiwi, apple, banana, cherry
PYchallenge.py
Run your code to check it…
Step 4

Check your understanding

1. What does the key argument of sorted() do?
2. How do tuples like (len(w), w) compare?
Last step

Your notes (saved on this device)

Tip: use and to move between lessons, K to search everything.

Your next ten minutes

Write Python that does something useful.

Start free. No install, no card, no passive video marathon.

Start learning free → Explore the path