Reduce function that is used for reducing the iterable (must take two arguments). (positional-only). Learn More about it here.
Parameter Details
function function that is used for reducing the iterable (must take two arguments). (positional-only)
iterable iterable that’s going to be reduced. (positional-only)
initializer start-value of the reduction. (optional, positional-only)
Overview
No import needed
No import required…
from functools import reduce # … but it can be loaded from the functools module
from functools import reduce # mandatory
reduce reduces an iterable by applying a function repeatedly on the next element of an iterable and the cumulative result so far.
def add(s1, s2):
return s1 + s2
asequence = [1, 2, 3]
reduce(add, asequence) # equivalent to: add(add(1,2),3)
Out: 6
In this example, we defined our own add function. However, Python comes with a standard equivalent function in the operator module:
import operator
reduce(operator.add, asequence)
Out: 6
reduce can also be passed a starting value:
reduce(add, asequence, 10)
Out: 16
Using reduce
def multiply(s1, s2):
print('{arg1} * {arg2} = {res}'.format(arg1=s1,
arg2=s2,
res=s1*s2))
return s1 * s2
asequence = [1, 2, 3]
Given an initializer the function is started by applying it to the initializer and the first iterable element:
cumprod = reduce(multiply, asequence, 5)
Out: 5 * 1 = 5
52=10 103=30
print(cumprod)
Out: 30
Without initializer parameter the reduce starts by applying the function to the first two list elements:
cumprod = reduce(multiply, asequence)
Out: 1 * 2 = 2
2*3=6
print(cumprod)
Out: 6
Cumulative product
import operator
reduce(operator.mul, [10, 5, -3])
Out: -150
Non short-circuit variant of any/all
it will not terminate the iteration before the iterable has been completely iterated over so it can be used to create a non short-circuit any() or all() function:
import operator
non short-circuit “all”
reduce(operator.and_, [False, True, True, True]) # = False
non short-circuit “any”
reduce(operator.or_, [True, False, False, False]) # = True
Must Read Python Interview Questions
200+ Python Tutorials With Coding Examples
Other Python Tutorials
- What is Python?
- Python Advantages
- Python For Beginners
- Python For Machine Learning
- Machine Learning For Beginners
- 130+ Python Projects With Source Code On GitHub