Combine results

Lesson 5 of 20 · Functional Python: values, behavior, and choices

Some transformations produce one result from many items. sum communicates a total directly; functools.reduce is useful when the combination is less familiar. It carries an accumulator, the result so far, from left to right.

from functools import reduce

def attach(acc, item):
    return acc + "/" + item

print(reduce(attach, ["north", "ridge"], "trail"))
print(reduce(attach, [], "trail"))
trail/north/ridge
trail

The first call to attach receives "trail" and "north"; its result becomes the accumulator for "ridge". The initial value is returned for an empty input. Without an initial value, reduce uses the first item as the accumulator; an empty input raises TypeError, and a single item is returned without calling attach.

trail + north -> trail/north + ridge -> trail/north/ridge

Order matters for noncommutative operations such as subtraction. The initial value is part of the meaning: starting a sum at zero makes sense, while starting a product at zero erases every product. Prefer sum, str.join, or a loop when they express the operation more clearly.

Chapter index