🧩 Functions, lesson 6 of 6
Lambdas, docstrings and functions as values
Pass functions around, write one-line lambdas and document your code.
11 min
1 exercise
2 quizzes
0/3 solved
Getting Python ready… examples can run in a moment.
In Python, functions are values, just like numbers and strings. You can store them in variables, lists and dicts, and pass them to other functions. Leave off the parentheses to refer to the function itself instead of calling it.
A tiny calculator
Add a mul function and a "*" entry to ops.
Pass a function in
apply_to_all doesn't care which function it gets. Try abs with some negative numbers.
A lambda is a tiny unnamed function written in one expression. Its result is returned automatically:
double = lambda n: n * 2
# same as: def double(n): return n * 2
Lambdas shine as short key= functions for
sorted, min and max.
Sort by what matters
key tells Python what to compare: the score, the lower-case word, the length.
What does this print?
A docstring is a string on the first line of a
function body that explains what it does. help()
shows it. Type hints (km: float,
-> float) document what goes in and out; Python
doesn't enforce them, but they make code easier to
read.
Document your function
Try help(len) to read a built-in function's docstring.
In sorted(words, key=len), why is there no () after len?
Count what matches
- Write
count_matching(items, test)that returns how many items maketest(item)returnTrue. Give it a docstring. - Use it with a lambda to set
long_wordsto the number of words longer than 4 letters.