Python: Define an empty-input result for functools.reduce
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.pyCaptured output:
Combined: 111
Empty: 0
Left fold: 5
Unseeded empty reduction rejectedZero 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.pyReference
Acknowledgements
This post was created with assistance from AI.