Python Reduce Function
Table Of Contents:
- What Is Python Reducer?
- How To Implement Python Reducer?
- Examples Of Python Reducer?
(1) What Is Python Reducer?
- If you want to apply some aggregate functions to an iterable like, adding, subtracting, multiplying, or concatenating all the values, then you can use the Python reduce() function.
- Python has an inbuilt reduce() function which you can import from “functools” module.
(2) How To Implement Python Reducer?
Syntax:
import functools
functools.reduce(function, iterable)
Arguments:
- function – This function will be applied to all the elements in an iterable in a cumulative manner to compute the result.
- iterable – Iterables are those python objects that can be iterated/looped over, includes like lists, tuples, sets, dictionaries, generators, iterators, etc.
(3) Examples Of Python Reducer?
Example-1:
import functools
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def addition(a,b):
return a+b
print('Addition:',functools.reduce(addition, lst))
Output:
Addition: 55
Explanation:
- First thing is to import the ‘functools‘.
- Second thing is to define your aggregate function.
- Here I have defined the addition function.
- I have passed the function name and the list as an argument to the reduce( ) function.
- reduce( ) function will add all the values from the list and give the result.
Example-2:
import functools
words = ['Hello ', 'How ', 'Are ', 'You ', 'Doing ', '?']
def concat(a,b):
return a + b
print(functools.reduce(concat, words))
Output:
Hello How Are You Doing ?
Explanation:
- Here I am concatenating the words inside the list.
Example-3:
import functools
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def multiply(a,b):
return a*b
print('Multiplication:',functools.reduce(multiply, lis))
Output:
Multiplication: 3628800
Explanation:
- Here I am multiplying the numbers inside the list.