Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
BUILD LAB / PYTHON/ Build your toolkit
EXPERIMENT 17 / 101

Small functions, sharp edges.

Use a tiny function where a clear sorting rule is all you need.

BY NAVAN SAMI◷ 6 MIN READPYTHON 3

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.

lambda.py
jobs = [{"name": "render", "minutes": 20}, {"name": "lint", "minutes": 2}]
ordered = sorted(jobs, key=lambda job: job["minutes"])

print([job["name"] for job in ordered])
↳ EXPECTED OUTPUT
['lint', 'render']

03 Under the hood

  1. 1

    sorted() returns a new list. The original jobs list keeps its existing order.

  2. 2

    The key function receives each job and returns the value used for comparison. The lambda extracts the minutes field.

  3. 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

A SMALL MISSION

Sort ["launch", "go", "build"] by word length using a lambda.

Reveal one possible solution +
one_possible_solution.py
words = ["launch", "go", "build"]
print(sorted(words, key=lambda word: len(word)))

05 Check your signal

QUICK SIGNAL CHECK

What does the key function provide to sorted()?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

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 ↗.

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.