Sub topic 7
Combining values with functools.reduce
This chapter assumes you can define functions with def, write a basic lambda, and use map and filter on lists. It also assumes you know how list comprehensions work. Here you will learn how functools.reduce folds a sequence into a single value, and when a simpler tool does the same job better.
What reduce does
map and filter return a sequence. reduce returns one value. It takes a function of two arguments, an iterable, and an optional initial value. It calls the function with a running result (the accumulator) and the next item, and the return value becomes the new accumulator.
reduce lives in functools. It is not a built-in in Python 3, so you must import it.
from functools import reduce
total = reduce(lambda acc, n: acc + n, [1, 2, 3, 4], 0)
print(total) # 10The lambda starts with acc = 0, the initial value. The steps are:
0 + 1gives11 + 2gives33 + 3gives66 + 4gives10
The initial value
The third argument is optional, but you should usually supply it. It has two effects.
- It sets the starting accumulator. Without it,
reduceuses the first item of the iterable as the starting accumulator and begins combining at the second item. - It is the result for an empty iterable. Without it, an empty iterable raises
TypeError.
from functools import reduce
print(reduce(lambda acc, n: acc + n, [], 0)) # 0
try:
reduce(lambda acc, n: acc + n, [])
except TypeError as error:
print(error)
# reduce() of empty iterable with no initial valueAn empty input is common in real programs, such as an empty cart or no matching rows. Supplying the initial value makes that case safe.
The accumulator can be any type
The accumulator does not have to match the item type. This is where reduce does work that sum cannot. The example below counts words by building a dictionary.
from functools import reduce
words = ["pear", "fig", "pear", "apple", "fig", "pear"]
def add_word(counts, word):
return {**counts, word: counts.get(word, 0) + 1}
print(reduce(add_word, words, {}))
# {'pear': 3, 'fig': 2, 'apple': 1}The function returns a new dictionary each time instead of changing the old one. This keeps the fold free of side effects. It also copies the dictionary at every step, which is slow on large inputs. For counting, collections.Counter is the better tool.
Common errors
- Swapped parameters. The accumulator comes first and the item second. Writing
lambda n, acc: ...runs without error but gives wrong results for any operation where order matters, such as subtraction. - No return value. A lambda always returns its expression. A
deffunction that forgetsreturnhandsNoneto the next step, and the next step usually fails. - Mutating the accumulator. Calling
acc.append(x)returnsNone, so the next step receivesNone. Return the new value instead. - Forgetting the import.
reducewithoutfrom functools import reduceraisesNameError.
When not to use reduce
Python has dedicated functions for the most common folds. They are shorter and easier to read.
| Goal | reduce version | Better version |
|---|---|---|
| Sum | `reduce(lambda a, b: a + b, xs, 0)` | `sum(xs)` |
| Product | `reduce(lambda a, b: a * b, xs, 1)` | `math.prod(xs)` |
| Largest | `reduce(lambda a, b: a if a > b else b, xs)` | `max(xs)` |
| All true | `reduce(lambda a, b: a and b, xs, True)` | `all(xs)` |
| Join strings | `reduce(lambda a, b: a + b, parts, "")` | `"".join(parts)` |
A case where reduce fits: composing functions
Composition applies several functions in order. Each function takes the result of the previous one, which is exactly a fold.
from functools import reduce
def compose(*funcs):
return lambda x: reduce(lambda acc, f: f(acc), funcs, x)
clean = compose(str.strip, str.lower, lambda s: s.replace(" ", "-"))
print(clean(" Hello Big World ")) # hello-big-worldHere the accumulator is the value being transformed, and each item is a function applied to it. The initial value x is the input.
Exercise
What does reduce(lambda acc, n: acc - n, [1, 2, 3], 10) return, and what happens if you remove the initial value 10?
Show answer
With the initial value, the steps are 10 - 1 = 9, 9 - 2 = 7, 7 - 3 = 4, so the result is 4. Without it, the accumulator starts at the first item: 1 - 2 = -1, then -1 - 3 = -4, so the result is -4. The initial value changes which item is treated as the start, and so it changes the answer for operations where order matters.
Exercise
Write a call to reduce that merges the list [{"a": 1}, {"b": 2}, {"a": 3}] into one dictionary. What is the result, and why does the value of "a" come out as it does?
Show answer
reduce(lambda acc, d: {acc, d}, [{"a": 1}, {"b": 2}, {"a": 3}], {}) returns {'a': 3, 'b': 2}. Each step copies the accumulator and then applies the next dictionary, so later dictionaries overwrite earlier values for the same key. The last dictionary sets "a" to 3.