Sub topic 7
Combining values with functools.reduce
This chapter assumes you can write a function with def, you know lists, tuples and dictionaries, and you have met lambda expressions and map and filter in earlier chapters. After it, you should be able to read and write functools.reduce calls and trace what they do. You should also know when a built-in or a plain loop is the better choice.
What reduce does
map turns a sequence into another sequence of the same length, and filter returns a shorter one. reduce collapses a sequence into a single value. It takes a function of two arguments, an iterable, and an optional starting value. It calls the function on the running result and the next item, and the return value becomes the new running result. This pattern is called a fold.
In Python 3 reduce is not a built-in. You import it from functools.
from functools import reduce
total = reduce(lambda acc, n: acc + n, [1, 2, 3, 4], 0)
print(total) # 10The lambda takes two parameters. By convention the first is the accumulator (acc), the result so far. The second is the current item. The call reduce(function, iterable, initial) is equivalent to this loop:
def my_reduce(function, iterable, initial):
acc = initial
for item in iterable:
acc = function(acc, item)
return accThe real reduce also accepts a call without initial, which we cover below. If you can read this loop, you can read any reduce call.
Tracing the steps
To see what happens, use a named function that prints its arguments.
from functools import reduce
def step(acc, n):
print(f"acc={acc}, n={n}")
return acc + n
print(reduce(step, [1, 2, 3, 4], 0))Output:
acc=0, n=1
acc=1, n=2
acc=3, n=3
acc=6, n=4
10Each return value feeds the next call as acc. The result of the last call is the result of reduce.
The initial value
The third argument is optional, and leaving it out changes behavior in two ways.
First, without initial, the first item of the iterable becomes the starting accumulator, and the function is first called on the first and second items:
from functools import reduce
def step(acc, n):
print(f"acc={acc}, n={n}")
return acc + n
print(reduce(step, [1, 2, 3, 4]))Output:
acc=1, n=2
acc=3, n=3
acc=6, n=4
10Second, an empty iterable then has nothing to start from. reduce raises an error:
from functools import reduce
from operator import add
print(reduce(add, [], 0)) # 0
print(reduce(add, [])) # TypeError: reduce() of empty iterable with no initial valueWith an initial value, an empty iterable simply returns that value. This is the main reason to supply one: code that works for three items should also work for zero.
The initial value matters for another reason. It sets the type of the accumulator, and it can differ from the type of the items. Suppose you want the total length of some strings:
from functools import reduce
words = ["lambda", "reduce", "fold"]
# Without an initial value, acc starts as the string "lambda",
# so acc + len(...) would try to add a str and an int.
total = reduce(lambda acc, w: acc + len(w), words, 0)
print(total) # 16Here the accumulator is an integer while the items are strings. Leaving out the 0 would raise a TypeError, because "lambda" + 6 is invalid. When the accumulator and the items have different types, always pass an initial value.
Order matters: reduce folds from the left
reduce processes items left to right. For operations like addition and multiplication the grouping does not change the answer. For others it does:
from functools import reduce
from operator import sub
print(reduce(sub, [10, 3, 2])) # 5, because (10 - 3) - 2
print(10 - (3 - 2)) # 9, the grouping reduce does NOT useIf your operation is not associative (grouping changes the result), the left-to-right order is part of the meaning. Subtraction, division and string formatting steps are common examples. Python has no built-in right fold. You can get one by reversing the iterable first, but you must then also swap the roles of the two arguments in your function.
Using the operator module instead of a lambda
Many reductions use a plain operator. The operator module has function versions of them, which are shorter than a lambda and a little faster:
from functools import reduce
from operator import add, mul
nums = [1, 2, 3, 4]
print(reduce(add, nums, 0)) # 10
print(reduce(mul, nums, 1)) # 24Choose the initial value as the identity element of the operation, which is the value that leaves any other value unchanged. It is 0 for addition, 1 for multiplication, "" for string concatenation and [] for list concatenation.
Prefer the built-ins when they exist
Many common reductions already have a named tool. Use it, because it states the intent.
| Goal | reduce version | Better |
|---|---|---|
| Sum | `reduce(add, xs, 0)` | `sum(xs)` |
| Product | `reduce(mul, xs, 1)` | `math.prod(xs)` |
| Largest | `reduce(max, xs)` | `max(xs)` |
| Any true | `reduce(or_, xs, False)` | `any(xs)` |
| All true | `reduce(and_, xs, True)` | `all(xs)` |
| Join strings | `reduce(add, strs, "")` | `"".join(strs)` |
The string case is more than style. reduce(add, strs, "") builds a new string at every step. "".join does the work in one pass.
The same cost appears with lists and dictionaries. This works but copies the accumulator on every step, so its running time grows quadratically with the input size:
from functools import reduce
lists = [[1, 2], [3], [4, 5]]
flat_slow = reduce(lambda acc, xs: acc + xs, lists, [])
print(flat_slow) # [1, 2, 3, 4, 5]For this job use itertools.chain.from_iterable:
from itertools import chain
lists = [[1, 2], [3], [4, 5]]
print(list(chain.from_iterable(lists))) # [1, 2, 3, 4, 5]Seeing the intermediate results with accumulate
Sometimes you want every running total, not only the last one. itertools.accumulate is the lazy relative of reduce. It yields the accumulator after each step:
from itertools import accumulate
from operator import mul
nums = [1, 2, 3, 4]
print(list(accumulate(nums))) # [1, 3, 6, 10]
print(list(accumulate(nums, mul))) # [1, 2, 6, 24]
print(list(accumulate(nums, initial=0))) # [0, 1, 3, 6, 10]The initial keyword needs Python 3.8 or later. When it is given, the initial value appears as the first element of the output. The last element of accumulate(...) equals the reduce result.
Reductions that build structures
reduce can build a dictionary or other object, as long as the accumulator is that object. Merging a list of dictionaries is a typical case:
from functools import reduce
configs = [{"a": 1}, {"b": 2}, {"a": 3}]
merged = reduce(lambda acc, d: {**acc, **d}, configs, {})
print(merged) # {'a': 3, 'b': 2}Later dictionaries override earlier keys. The lambda returns a new dictionary each time, so the original configs stay untouched.
A common mistake is to mutate the accumulator inside the function and forget to return it:
from functools import reduce
def collect(acc, x):
acc.append(x) # returns None, not the list
# reduce(collect, [1, 2, 3], []) -> second call fails: None has no attribute 'append'The function must always return the new accumulator. Mutating the initial value is also risky, since reduce does not copy it. If you pass a list or dictionary you created elsewhere, reduce changes that object. Prefer returning new objects, or create the initial value inside the call, as in reduce(..., {}).
Composing functions with reduce
Because reduce can fold any binary operation, it can fold functions, too. Here the accumulator is itself a function:
from functools import reduce
def compose(*funcs):
return reduce(lambda f, g: lambda x: g(f(x)), funcs, lambda x: x)
clean = compose(str.strip, str.upper, lambda s: s + "!")
print(clean(" hello ")) # HELLO!The initial value is the identity function, which makes compose() with no arguments valid. Each step wraps the previous function in a new one. The inner lambda sees f and g as parameters of the outer lambda, and each call of the outer lambda has its own f and g. So the late-binding pitfall from the closures chapter does not apply here.
This is compact, but it is dense to read. A team that is not used to folds may prefer an explicit loop for this.
When reduce is the right tool
Use reduce when all of the following hold:
- The operation combines two values into one of the same kind as the accumulator.
- No built-in (
sum,max,any,"".join,math.prod) already does the job. - The step is short enough to read as one expression or a small named function.
Use a for loop when the step needs several statements, when you update more than one variable, or when you need break or early exit. A loop with a named accumulator is often clearer than a lambda with two cryptic parameter names. If the function is more than a one-liner, give it a name with def, which also makes the trace example above easy to reproduce.
Summary of edge cases
reduce(f, [])with no initial value raisesTypeError.reduce(f, [x])with no initial value returnsxwithout ever callingf.reduce(f, [], init)returnsinit.- The accumulator type comes from the initial value, or from the first item if none is given.
- The fold runs left to right. Non-associative operations follow that order.
- The function must return the new accumulator on every call.
Exercise
Predict the output of each line, then explain the third one. from functools import reduce from operator import add, sub print(reduce(add, [5], 0)) print(reduce(add, [5])) print(reduce(sub, [20, 5, 3], 0))
Show answer
The first line prints 5 (0 + 5). The second prints 5 as well: with one item and no initial value, reduce returns that item without calling add. The third prints -28. With the initial value 0, the steps are (0 - 20) = -20, then -20 - 5 = -25, then -25 - 3 = -28. Without the initial value the result would be (20 - 5) - 3 = 12, because the first item would become the accumulator.
Exercise
Write a function longest(words) that uses functools.reduce to return the longest word in a list. If two words have the same length, the earlier one must win. What should it do for an empty list, and how do you make that happen?
Show answer
from functools import reduce def longest(words): return reduce(lambda a, b: b if len(b) > len(a) else a, words, "") The comparison uses > so a tie keeps the earlier word a. The initial value "" makes an empty list return "" instead of raising TypeError. In real code, max(words, key=len, default="") does the same job, because max returns the first maximal item in a tie, and it is the better choice.