Skip to the workspace
Pebellslearn by building
Functional Python  ›  Lesson

Lambdas, map, filter & reduce

Lambdas 21 minA lambda creates a small function expression. map transforms values, filter selects values and reduce combines them into an accumulated result.

A lambda creates a small function expression. map transforms values, filter selects values and reduce combines them into an accumulated result.

Follow one item through a transformation chain and check the roles of selection, conversion and aggregation.

A small function can become a sorting rule, a transformation, or a filter. lambda is a compact expression for creating that function; map and filter decide when to call it as their iterators are consumed. Follow one order through the chain, then combine values with a fold whose initial value also handles empty input.

Two machines on one belt: a small gear-box labelled "lambda x: x * 2" with prices 20, 30 rolling in and 40, 60 rolling out (map); below it a sieve labelled "lambda o: not o.cancelled" with five orders falling in and only the active ones dropping through, the cancelled ones caught above the mesh (filter)

Sort orders by price

A café app lists today's orders, cheapest first. sorted() takes a key function it calls once per item — a perfect one-line job for a lambda:

python

key=lambda o: o["price"] just names which field to compare — it never runs on its own, only when sorted calls it. Writing a whole def by_price(o): return o["price"] above the call would work identically, but for a one-line rule read right where it's used, the lambda is clearer.

A lambda can only hold one expression — no = assignment, no for, no if statement (a ternary a if cond else b is fine, because that's an expression too):

What happens when you run this?
mark_cheap = lambda price: cheap = price < 50
print(mark_cheap(30))

Preparing this topic’s interactive investigation…

Double every price with map

The café wants a festival menu at double the price. map() applies one function across a whole list and hands back an iterator:

What happens when you run this?
prices = [20, 60, 90]
doubled = map(lambda p: p * 2, prices)
print(doubled[0])

That laziness has a second trap: a map (or filter) object is used up the moment you read it once.

broken — fix it

Run it: the final count prints 0, not 3. Store the list once and read it twice.

Filter out cancelled orders, then total the rest

filter() keeps only the items a function approves of. Chain it with map() and functools.reduce() and you can read a whole pipeline left to right — keep the active ones, pull out their prices, fold them into one total:

python

reduce calls its lambda on the running total and the next price, over and over, until one number is left: 0+20=20, then 20+30=50. The starting value (0 here) also protects against an empty list — without it, reduce on an empty sequence raises TypeError.

Once the "keep, then combine" logic needs more than one line — say, also logging each cancelled order's name — a plain for loop or a named def reads better than three chained lambdas. Lambdas earn their place when they stay this short.

Follow one item through filter, map, and reduce

An iterator is a one-way position in a sequence: requesting the next value advances it. filter and map create these positions; they do not compute whole result lists when constructed. The final consumer pulls work through the chain.

python

The first log is empty. To produce 6, the next pull tests -1, rejects it, tests 3, then doubles 3. It has not processed 4. Named functions make this mechanism visible; lambdas would change the spelling, not the order.

reduce(combine, items, initial) keeps an accumulator. For prices 20, 30 with initial 0, the calls are combine(0, 20), then combine(20, 30). An initial value defines the empty-input result too. Use sum when addition is the entire job; the exercise requests reduce to practise the general fold.

For a transfer, replace addition with string concatenation and predict the empty-input result. Then try filter(None, [0, 1, "", "ok"]): it removes all falsey values, which may be wrong if zero is a valid reading. Multiple-input map stops at the shortest iterable by default, so uneven lengths require an explicit policy rather than silently assuming all records were paired.

Quick practice

What does this print?
nums = [1, 2, 3, 4, 5]
evens = filter(lambda n: n % 2 == 0, nums)
print(list(evens), list(evens))
What does this print?
from functools import reduce
words = ["ok"]
print(reduce(lambda a, b: a + " " + b, words))
broken — fix itNameError

Fix the sort so it runs, ordering names by length.

What happens when you run this?
prices = []
from functools import reduce
print(reduce(lambda a, b: a + b, prices))

🎯 Your turn

Write active_total(orders). Each order is a dict with "price" and "cancelled". Filter out the cancelled ones, map each remaining order to its price, then reduce those prices to one total (start at 0).

  • active_total([{"price": 20, "cancelled": False}, {"price": 15, "cancelled": True}]) → 20
  • active_total([]) → 0

Hint: filter(lambda o: not o["cancelled"], orders), then map(lambda o: o["price"], ...), then functools.reduce(lambda a, b: a + b, ..., 0).

Press ▶ Run, try the Live App chips, then ✓ Check. After that, the practice set below goes from one lambda to a full filter-map-reduce pipeline.

Your task
Write active_total(orders). Each order is a dict with "price" and "cancelled". Filter out the cancelled ones with filter(lambda o: not o["cancelled"], orders), map each remaining order to its price with map(lambda o: o["price"], ...), then fold those prices into one total with functools.reduce(lambda a, b: a + b, ..., 0). Example: active_total([{"price": 20, "cancelled": False}, {"price": 15, "cancelled": True}]) -> 20.

Practice — level up

0/5 solved

Solve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.

Warm-upDouble every number with map

Write double_all(nums) that returns a LIST with every number in nums doubled, using map and a lambda.

lambdamap
DrillKeep only even numbers with filter

Write keep_evens(nums) that returns a LIST of only the even numbers in nums, using filter and a lambda.

lambdafilter
Buildmap over two lists at once

Write pairwise_sums(a, b) that returns a LIST where item i is a[i] + b[i], using ONE map call with a two-argument lambda (map can take more than one iterable).

lambdamap
BossMultiply everything with reduce

Write product_of(nums) that returns the product of every number in nums, using functools.reduce. An empty list should return 1 (the product of nothing) — give reduce a starting value to make that work.

lambdareduce
Capstonefilter, map and reduce in one pipeline

Each item is a (price, is_active) tuple. Write total_active_value(items) that returns the total price of only the active items, built as ONE pipeline: filter the active ones, map them to their price, then reduce to a total (start at 0).

lambdamapfilterreduce
Project context and further resources
active_total.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
active_total(orders) → intFilter out cancelled orders, map to price, reduce to one total.
try:
returned
No app map for this section yet.
Press Run to execute your code.
Press Check to run the tests for this lesson.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.