Python Lambdas, map() and filter()
PCAP objective 5.2 is embed lambda functions into code. A lambda is a function written as a single expression, with no name and no return - the expression *is* the return value. It exists because sorted, map and filter want a small function passed in, and writing a def for it is often noise. map and filter return lazy iterators, and reduce is not a built-in at all.
Comprehensions and Lambdas Guide 21 of 25 Intermediate
- OSUbuntu 26.04 LTS
- Python3.14.4
- pip25.1.1
- TimeAbout 16 min
map and filter return iterators in Python 3; in Python 2 they returned lists. reduce was moved out of the built-ins into functools in Python 3. Both differences appear on this page and both trip up older material.
| Server Name | IP Address | OS | Roles | CPU | RAM | HDD |
|---|---|---|---|---|---|---|
| RUNNER01 | 192.168.0.27 | Ubuntu 26.04 LTS | Python 3.14.4 - the only machine this path needs | 2 Core | 4 GB | 50 GB |
This guide includes
Use this for the lambda objective. This matters because map and filter hand back single-use iterators - so whatever reads one second gets nothing at all.
- writing a lambda, whose body must be a single expression
- using them where they belong, as the
keytosorted,minandmax - using
mapandfilter, including thefilterform nobody teaches - finding that both are single-use
- using
reduce, and seeing what happens without the import
Before you start
-
A lambda is a function with no name
-
One expression, and nothing else
-
A lambda that returns nothing useful
-
Where lambdas are actually used
-
map
-
filter, including the form nobody teaches
-
map and filter are single-use
-
reduce, which is not a built-in
-
reduce without the import
-
What the exam does with this objective