Folding a Sequence With reduce

Concepts covered: Flexible Arguments

functools.reduce takes a function of 2 arguments and a sequence, and folds the sequence into a single value. It calls the function on the first 2 items, calls it again on that result and the third item, and keeps going left to right until the items run out. The function's first parameter is the running result, called the accumulator. The second parameter is the next item.

Watch it fold 4 batch row counts. The step function prints every call, so you can follow the accumulator from call to call.

from functools import reduce

def add_rows(running, batch):
    total = running + batch
    print(f"{running} + {batch} -> {total}")
    return total

batches = [120, 45, 300, 15]
total = reduce(add_rows, batches)
print("total:", total)
120 + 45 -> 165
165 + 300 -> 465
465 + 15 -> 480
total: 480

Giving reduce a starting value

A third argument, the initializer, becomes the first accumulator, and the step then runs once per item: 4 batches make 4 calls. The initializer matters in 2 situations. The first is a sequence that can be empty. With no initializer and no items, reduce has nothing to return and raises TypeError: reduce() of empty sequence with no initial value, while reduce(add_rows, [], 0) returns 0. The second is a result whose type differs from the items. One case is a list of table names, which are strings, folded into a total character count, which is an int:

from functools import reduce

def add_length(total, name):
    return total + len(name)

tables = ["orders", "users", "refunds"]
print(reduce(add_length, tables, 0))

Output:

18

With 0, the first call is add_length(0, "orders"), and the total stays an int: 6, then 11, then 18. Drop the 0 and the first item, the string "orders", becomes the accumulator. The first call then runs "orders" + len("users"), which is "orders" + 5, and Python raises TypeError: can only concatenate str (not "int") to str. Without an initializer, the accumulator starts out as the first item, with that item's type.

The dict merge below needs its {} for the first situation. Each file reports row counts per table, the items and the result are both dicts, and on some nights the job receives no files at all. The step copies the accumulator with dict(acc) before adding to it, so it stays pure and returns a new value on every call.

from functools import reduce

def merge_counts(acc, counts):
    merged = dict(acc)
    for table, n in counts.items():
        merged[table] = merged.get(table, 0) + n
    return merged

files = [
    {"orders": 3, "users": 1},
    {"orders": 2},
    {"users": 4, "refunds": 1},
]
print(reduce(merge_counts, files, {}))
print(reduce(merge_counts, [], {}))

Output:

{'orders': 5, 'users': 5, 'refunds': 1}
{}

Delete both {} arguments and the first file's dict becomes the starting accumulator. The first print stays the same, because merge_counts copies whatever accumulator it receives. The second call then raises the TypeError instead of printing {}.

Order matters, and operator helps

Since the fold runs left to right, the grouping is fixed: reduce(f, [a, b, c]) computes f(f(a, b), c). For addition and merging counts, grouping makes no difference to the answer. For subtraction or division it does. The operator module provides Python's operators as named functions, such as operator.add, operator.mul and operator.getitem, so you can pass them to reduce without writing a def for each.

from functools import reduce
import operator

event = {"user": {"address": {"city": "Lisbon"}}}
path = ["user", "address", "city"]

print(reduce(operator.getitem, path, event))
print(reduce(operator.mul, [2, 3, 4], 1))

Output:

Lisbon
24

operator.getitem(d, k) returns d[k], so folding a key path over a nested record descends a level per key: event["user"], then ["address"], then ["city"]. The 1 initializer for the product works the way 0 does for a sum: it is the value that leaves the result unchanged.

What does this print?

from functools import reduce
import operator

print(reduce(operator.sub, [10, 3, 2]))

When a plain loop reads better

Reduce reads well when the step is a single named operation and the accumulator is a single value. It reads worse when the accumulator carries several pieces of state or the step needs branches. Here is an average computed both ways:

from functools import reduce

readings = [4, 8, 6]

def step(acc, value):
    count, total = acc
    return (count + 1, total + value)

count, total = reduce(step, readings, (0, 0))
print(total / count)

count, total = 0, 0
for value in readings:
    count += 1
    total += value
print(total / count)

Output:

6.0
6.0

Both print 6.0. The loop names each piece of state on its own line, while the reduce version packs count and total into a tuple that the reader unpacks mentally at every call. For totals, largest values and smallest values, sum(), max() and min() beat both, since each names its intent in a word.

Do
  • Use reduce when the step is a single named function, like operator.add or merge_counts
  • Pass an initializer whenever the sequence can be empty
  • Return a new accumulator from the step instead of changing the old one
Avoid
  • Don't use reduce to total or find the largest or smallest; use sum, max or min
  • Don't pack 3 or more pieces of state into a tuple accumulator; write the loop
  • Don't put branches in a step function the reader must trace call by call

About this lesson

This section is part of the Functional Programming: Intermediate lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.