CodeBlanks Logo Icon CodeBlanks

functools.reduce

Learn accumulation with functools.reduce.

functools.reduce

functools.reduce folds a sequence into a single value. It applies a two-argument function repeatedly: at each step it combines the accumulated value with the next item.

The syntax is reduce(fn, seq, initial). fn(accumulator, item) is called for each item.

from functools import reduce

nums = [1, 2, 3, 4]
total = reduce(lambda a, b: a + b, nums, 0)
print(total)  # 10

Without an initial value, the first item of the sequence is used. Providing an initial value is safer for empty sequences.

Product and chaining with reduce

reduce is not just for sums. Use lambda a, b: a * b for products; the initial value must be 1 (since 1 is the multiplicative identity).

The initial value matters: 0 for sums, 1 for products, "" for string concatenation. A wrong initial value corrupts the result.

Without an initial value, reduce on an empty sequence raises TypeError. Safe code always provides one.

Practice Compute a product with reduce

Compute the product of nums = [2, 3, 4] with reduce. Use lambda a, b: a * b as the combiner and 1 as the initial value. Print the result.

Starter code

main.py
from functools import reduce

nums = [2, 3, 4]
# use reduce with a multiplication combiner and initial 1
# print the result

Sample solution

main.py
from functools import reduce

nums = [2, 3, 4]
result = reduce(lambda a, b: a * b, nums, 1)
print(result)

Expected output

24

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the reduce call

Question
from functools import reduce

nums = [1, 2, 3, 4]
total = ____(lambda a, b: a + b, nums, 0)
print(total)
Answer
from functools import reduce

nums = [1, 2, 3, 4]
total = reduce(lambda a, b: a + b, nums, 0)
print(total)

Explanation: reduce(lambda a, b: a+b, nums, 0) folds the list into a sum; the result is 10.

2 Match the reduce steps

Term Meaning
fn(accumulator, item) Per-step call
initial=0 Starting accumulator
lambda a, b: a+b Summing combiner
reduce Fold operation

3 What should the reduce initial value be for a product?

  • 1 Correct answer
  • 0
  • Empty string ""
  • None

Explanation: 1 is the multiplicative identity; starting at 1 keeps the product correct.

All lessons in Advanced