Skip to the solution
MediumDSA12 min read

How does functools.reduce fold a sequence?

532 views

The problem

Question presented to candidate: "What does functools.reduce do, step by step? What happens with an empty list, and when would you choose it over a loop or a built-in like sum?"

What a strong answer should cover:

  • reduce(f, iterable[, initial]) is a left fold: it keeps an accumulator and calls acc = f(acc, item) for each item, returning the final accumulator β€” reduce(f, [a, b, c]) is f(f(a, b), c).
  • Without initial, the first item is the starting accumulator (so f runs n-1 times); with initial, f runs n times and initial also fixes the result type.
  • Edge cases: an empty iterable with no initializer raises TypeError; a single item is returned without calling f; initial is positional only (a keyword raises TypeError on 3.11-3.13).
  • Left fold means order matters for non-associative operations (reduce(sub, [1, 2, 3, 4]) is -8); a right fold needs reversed and a flipped function.
  • When to use it: composing functions, walking nested keys, merging or intersecting many collections. Prefer sum, math.prod, max, all, any, "".join or a plain loop when they fit β€” clearer and faster. It moved out of the built-ins into functools in Python 3.

Code / implementation expected: Optional β€” trace a small fold, or implement reduce with a loop.

  • functools
  • reduce

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

12 min read Β· 12 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonTrace the fold: initializer, left fold, edge cases and a hand-written reduce
PythonReal uses of reduce, built-in alternatives and the quadratic trap

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 82 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextMedium

How do default, keyword-only and positional-only parameters work?

Continue