Skip to content
Python: Define an empty-input result for functools.reduce

Python: Define an empty-input result for functools.reduce

November 25, 2026

When a reduction may receive no records, supply an initializer that defines the empty result. It is also the first accumulator value, so choose it for the operation rather than adding an arbitrary fallback afterward.

Tested on Linux with Python 3.12.14. Use Python 3.12 or newer. The example uses only the standard library and requires no network access.

Run the example

Save this as reduction_seed_demo.py in an empty working directory:

from functools import reduce
from operator import or_

permissions = [0b001, 0b100, 0b010]
print("Combined:", format(reduce(or_, permissions, 0), "03b"))
print("Empty:", reduce(or_, [], 0))
print("Left fold:", reduce(lambda total, value: total - value, [3, 2], 10))
try:
    reduce(or_, [])
except TypeError:
    print("Unseeded empty reduction rejected")

Run it without -O so any assertions remain enabled:

python3 reduction_seed_demo.py

Captured output:

Combined: 111
Empty: 0
Left fold: 5
Unseeded empty reduction rejected

Zero is the identity for this integer bitwise OR operation. An empty input therefore yields zero. The subtraction example gives 5 because reduction proceeds as (10 - 3) - 2; the initializer participates in the calculation.

Limits and cleanup

In Python 3.12, pass the initializer as the third positional argument. If an empty input is an application error, validate it instead of silently choosing an identity. Prefer sum() for ordinary numeric addition and keep custom reduction functions free of unintended side effects.

After testing, remove the example script from its working directory:

rm -- reduction_seed_demo.py

Reference

Python 3.12 documentation

Acknowledgements

This post was created with assistance from AI.

Last updated on