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 callsacc = f(acc, item)for each item, returning the final accumulator βreduce(f, [a, b, c])isf(f(a, b), c).- Without
initial, the first item is the starting accumulator (sofruns n-1 times); withinitial,fruns n times andinitialalso fixes the result type. - Edge cases: an empty iterable with no initializer raises
TypeError; a single item is returned without callingf;initialis positional only (a keyword raisesTypeErroron 3.11-3.13). - Left fold means order matters for non-associative operations (
reduce(sub, [1, 2, 3, 4])is-8); a right fold needsreversedand a flipped function. - When to use it: composing functions, walking nested keys, merging or intersecting many collections. Prefer
sum,math.prod,max,all,any,"".joinor a plain loop when they fit β clearer and faster. It moved out of the built-ins intofunctoolsin Python 3.
Code / implementation expected: Optional β trace a small fold, or implement reduce with a loop.