Small functions, sharp edges.
Use a tiny function where a clear sorting rule is all you need.
01 The idea
A lambda expression creates a function from a single expression. It is useful as a short callback, especially when you need a sort key. Prefer a named def function when logic needs multiple steps, a docstring, or a reusable explanation.
02 The experiment
Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.
jobs = [{"name": "render", "minutes": 20}, {"name": "lint", "minutes": 2}]
ordered = sorted(jobs, key=lambda job: job["minutes"])
print([job["name"] for job in ordered])['lint', 'render']
03 Under the hood
- 1
sorted() returns a new list. The original jobs list keeps its existing order.
- 2
The key function receives each job and returns the value used for comparison. The lambda extracts the minutes field.
- 3
A lambda implicitly returns the result of its expression. If your callback is getting difficult to read, pull it out into a named function instead of making the expression denser.
04 Your turn, builder
Sort ["launch", "go", "build"] by word length using a lambda.
Reveal one possible solution +
words = ["launch", "go", "build"]
print(sorted(words, key=lambda word: len(word)))05 Check your signal
What does the key function provide to sorted()?
Experiment. Logged.
When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.
Keep exploring
Go deeper with the official Python guide ↗.