Skip to content
dreamcode
dreamcode
Map
Lambda & sorting
Lesson 38 of 77
+15 XP on finish
PYTHON INTERMEDIATEChapter 6 · Comprehensions and data tools

Sorting with keys and lambda

sorted() and .sort() accept a key function that turns each item into the value to sort by. A lambda is a tiny one-line function without a name: lambda s: s["mag"] takes an item and returns its magnitude. Add reverse=True for largest first. min() and max() accept the same key.

Worked example

How it reads

  • key= is called once per item; the list is ordered by what it returns
  • lambda s: s["mag"] is the same as a small def that returns s["mag"]
  • Built-ins like len can be keys too: key=len
Cloud tip: To sort by two things, return a tuple: key=lambda p: (p["team"], p["score"]).
main.py
PYTHON
real Python, runs in your browser
Console
Run your code to see its output here.
YOUR TURN

Sort the crew by age, youngest first, and print it: [('Luka', 9), ('Nova', 12), ('Mira', 15)].

Press Run to check your work.