L3·Functions & Modules

λLambdas & Higher-Order Functions

Anonymous functions and map/filter/sorted.

lambdamapfiltersortedkey

§ 1lambda

lambda params: expression — one expression only. Not for statements.

§ 2map / filter

Lazy iterators. Often clearer as comprehensions.

§ 3sorted(key=...)

key is a function called once per item — the classic lambda use case.

Example

1people = [("Ada", 36), ("Bob", 42), ("Cai", 29)]
2by_age = sorted(people, key=lambda p: p[1])
3print(by_age)

Try it live · Python runs in your browser

Loading playground…

Checkpoint quiz

Question 1 / 2
How many statements can a lambda body contain?