Lambdas, docstrings and functions as values

Functions, lesson 6 of 6

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

Example

A tiny calculator

Add a mul function and a "*" entry to ops.

Example

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.

Example

Sort by what matters

key tells Python what to compare: the score, the lower-case word, the length.

Quiz

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.

Example

Document your function

Try help(len) to read a built-in function's docstring.

Quiz

In sorted(words, key=len), why is there no () after len?

Exercise

Count what matches

  1. Write count_matching(items, test) that returns how many items make test(item) return True. Give it a docstring.
  2. Use it with a lambda to set long_words to the number of words longer than 4 letters.