Sorting: sorted(), Keys & Custom Order
Lesson 3 of 5 · View course roadmap
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): alphabeticalsorted(words, key=len): by length; the key function is called on each item and the results are compared insteadsorted(words, key=lambda w: (len(w), w)): by length, ties broken alphabetically, tuples compare position by positionreverse=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"]).
Try it yourself
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”.
Output appears here…
Pass the challenge +35 XP
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.
apple, banana, cherry, fig, kiwi fig, kiwi, apple, banana, cherry
", ".join(sorted(words)) for line one; key=lambda w: (len(w), w) for line two.
words = ["banana", "fig", "cherry", "kiwi", "apple"]
print(", ".join(sorted(words)))
print(", ".join(sorted(words, key=lambda w: (len(w), w))))
Run your code to check it…
Check your understanding
Your notes (saved on this device)
Tip: use ← and → to move between lessons, ⌘K to search everything.