Thursday, 23 September 2021

Python: reduce function support

'functools.reduce' method apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value.

 

Signature

functools.reduce(function, iterable[, initializer])

Example 1: find sum of list of numbers

sum_of_numbers = functools.reduce(lambda x, y : x + y, numbers, 0)

The left argument, x, is the accumulated value and the right argument, y, is the update value from the iterable. Third argument ‘initializer’ is optional, initializer is present, it is placed before the items of the iterable in the calculation, and serves as a default when the iterable is empty.

 

Example 2: Find product of list of numbers

product_of_numbers = functools.reduce(lambda x, y : x * y, numbers, 1)

Find the below working applicaiton

 

reduce_demo_1.py

import functools

numbers = [1, 2, 3, 4, 5]

sum_of_numbers = functools.reduce(lambda x, y : x + y, numbers, 0)
product_of_numbers = functools.reduce(lambda x, y : x * y, numbers, 1)

print('numbers -> ', numbers)
print('sum_of_numbers -> ', sum_of_numbers)
print('product_of_numbers -> ', product_of_numbers)

Output

numbers ->  [1, 2, 3, 4, 5]
sum_of_numbers ->  15
product_of_numbers ->  120


  

Previous                                                    Next                                                    Home

No comments:

Post a Comment