Fold an iterable into one accumulated result.
What You Will Learn
reduce(function, iterable, initializer) repeatedly combines the accumulator with the next value. An explicit initializer makes empty input behavior predictable.
Step-by-Step Example
The example below makes the behavior visible with small input values that you can change safely.
from functools import reduce
quantities = [2, 3, 4]
print(reduce(lambda left, right: left * right, quantities, 1))
How the Example Works
- The imports provide the standard-library tools used in the demonstration: functools.
- The variable quantities holds the result of [2, 3, 4]. Later lines use that value or inspect how it changes.
- The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.
For the chosen input, the expression reduce(lambda left, right: left * right, quantities, 1) prints 24. Compare that result with the rule above before you change the argument.
Expected output from the example:
24
When You Would Use This
These tools are useful when composing small reusable functions, adapting callbacks, or eliminating repeated work. Pay attention to whether the operation returns a new object, updates state, or produces lazy results. Test a small success case and a boundary case before integrating it into an application.
Practice: Modify the Code
Compute a product of item quantities and compare with math.prod().
Verify the changed output against the behavior described above, including the relevant invalid or boundary case.
For complete parameters and version details, consult the official Python documentation.
Common Beginner Mistakes
- Forgetting an initializer when the iterable might be empty.
- Using a wrapper without checking which original function, arguments and return values it preserves.
Key Takeaways
- Fold an iterable into one accumulated result.
- reduce(function, iterable, initializer) repeatedly combines the accumulator with the next value.
- Apply this operation only after checking the assumptions and input conditions shown in the example.