BeginnerCoder

Lesson 19 — functools.reduce

Fold a sequence

reduce(fn, items) collapses a list into one value. It calls fn with the first two items, then calls fn again with that result and the next item, and so on to the end. You can pass a start value as a third argument.

from functools import reduce
print(reduce(lambda a, b: a if a > b else b, [3, 9, 4]))  # 9

Why it matters: it expresses running products, totals and merges in one line.

Want it another way?
Task

Use reduce to multiply all numbers together and print the result.

Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.

Keep going with Python Intermediate

Ready for more? Optional paid resources that pick up where this lesson leaves off.

Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.