Batu Lab NotesPractical developer guides

Use reduce with an explicit identity for an empty input

By Batu ยท English technical notes

Also published in our Blogger archive.

Use reduce with an explicit identity for an empty input

By Batu

functools.reduce() combines an iterable by repeatedly calling a two-argument function. Without an initializer, an empty iterable has no first value to return, so reduce() raises TypeError. Supplying an explicit identity makes the result defined even when there are no elements.

Here the reducer is operator.add and the identity is 0. For the list [8, -3, 5], the calls conceptually form ((0 + 8) + -3) + 5, producing 10. For [], no additions occur and the answer remains 0. The assertions cover both cases, while the printed output makes the example deterministic.

Choose an identity that matches the operation and result type. Multiplication normally uses 1; concatenating tuples can use (). An identity is not merely a fallback value: it participates in the calculation, so using 0 with a string or "" with numeric addition would be an input/type mistake. Also, reduce() is best reserved for an operation that is naturally associative enough for the intended order; floating-point addition can vary with ordering because rounding occurs at each step.

AI assistance was used to draft this article.

from functools import reduce
from operator import add

numbers = [8, -3, 5]
empty_numbers = []

total = reduce(add, numbers, 0)
empty_total = reduce(add, empty_numbers, 0)

assert total == 10
assert empty_total == 0
print(total)
print(empty_total)

Expected stdout:

10
0

Sources