Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 5.6 — Functions Are Values: Passing Them Around
Python · Example 1 of 3

Passing, storing and returning functions

shout and whisper are passed to apply, stored in a dict, and returned from pick.

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.

01

Write apply_twice(func, value) that returns func(func(value)). Test it with a function that adds 3, and with str.upper.

02

Sort the list ["pear", "fig", "banana", "kiwi"] by length, and break ties alphabetically, using one sorted call.

03

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

01

What does it mean that functions are first-class values in Python?

02

What is a lambda, and when should you prefer def?

03

What is the difference between key=len and key=len()?

04

When would you choose a comprehension over map and filter?

05

How does a dispatch table work, and why is it used for tool calling?

Passing, storing and returning functions
Sign in to run this example in your browser.

Expected output

HELLO!
hello...
loud -> GOOD MORNING!
quiet -> good morning...
wait...
type: function
name: shout
True True False