Saturday 5 November 2022

Reduce function in Python

The reduce(fun,seq) function is used to apply a particular function passed in its argument to all of the list elements mentioned in the sequence passed along.

Working :  

  • At first step, first two elements of sequence are picked and the result is obtained.
  • Next step is to apply the same function to the previously attained result and the number just succeeding the second element and the result is again stored.
  • This process continues till no more elements are left in the container.
  • The final returned result is returned and printed on console.

 

Example using lambda function (Summing Numeric Values)

In this example, we have defined a lambda function that calculates the sum of two numbers on the passed list as an iterable using the reduce function.

Code:

from functools import reduce 

nums = [1, 2, 3, 4]
ans = reduce(lambda x, y: x + y, nums)
print(ans) 

Output:

10

The above python program returns the sum of the whole list as a single value result which is calculated by applying the lambda function, which solves the equation (((1+2)+3)+4).

Source : https://www.scaler.com/topics/reduce-function-in-python/

No comments:

Post a Comment