key=, lambda, map and filter
The key function says what to compare. map is lazy, so the last line shows its type.
In Python a function is an object like any other: you can store it in a variable, put it in a list or dict, pass it to another function, and return it. That idea powers sorted(key=...), map, filter, small lambda functions, and the tool tables that let AI models call your code.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write apply_twice(func, value) that returns func(func(value)). Test it with a function that adds 3, and with str.upper.
Sort the list ["pear", "fig", "banana", "kiwi"] by length, and break ties alphabetically, using one sorted call.
Make a dispatch table OPS for "add", "sub" and "mul" (use lambdas) and a function calculate(op, a, b) that looks the operation up and calls it. Unknown operations should return None.
Explain it without notes
What does it mean that functions are first-class values in Python?
What is a lambda, and when should you prefer def?
What is the difference between key=len and key=len()?
When would you choose a comprehension over map and filter?
How does a dispatch table work, and why is it used for tool calling?
Expected output
['fig', 'apple', 'banana', 'cherry']
['banana', 'apple', 'fig', 'cherry']
['cherry', 'banana', 'apple', 'fig']
[1, 4, 9, 16, 25, 36]
[2, 4, 6]
[4, 16, 36]
('Ravi', 95)
map