How to Use Reduce Function in Python: Simple Guide
In Python, the
reduce function from the functools module applies a function cumulatively to the items of an iterable, reducing it to a single value. You use it by passing a function and an iterable to reduce, which combines the elements step-by-step.Syntax
The reduce function has this syntax:
reduce(function, iterable[, initializer])
function: a function that takes two arguments and returns one value.
iterable: a sequence like a list or tuple.
initializer (optional): a starting value that is placed before the items of the iterable.
python
from functools import reduce result = reduce(function, iterable, initializer)
Example
This example shows how to use reduce to multiply all numbers in a list:
python
from functools import reduce def multiply(x, y): return x * y numbers = [1, 2, 3, 4] result = reduce(multiply, numbers) print(result)
Output
24
Common Pitfalls
Common mistakes include:
- Not importing
reducefromfunctools. - Using a function that does not take exactly two arguments.
- Forgetting that
reducereturns a single value, not a list.
Example of a wrong and right way:
python
from functools import reduce # Wrong: function takes one argument # def add(x): # return x + 1 # Right: function takes two arguments def add(x, y): return x + y numbers = [1, 2, 3] result = reduce(add, numbers) print(result) # Output: 6
Output
6
Quick Reference
Tips for using reduce:
- Always import it:
from functools import reduce. - The function must take two inputs.
- Use
initializerto set a starting value if needed. - It returns a single value, not a list.
Key Takeaways
Import reduce from functools before using it.
Reduce applies a two-argument function cumulatively to an iterable.
It returns a single combined value, not a list.
Use an initializer to set a starting point if needed.
Ensure the function passed to reduce takes exactly two arguments.