Home »
Python
Python reduce() with Lambda Function
By IncludeHelp Last updated : December 08, 2024
Python reduce() with Lambda Function
The reduce() function applies on each element of an iterable collection and returns the reduced (based on applied calculation through the function) value.
The lambda function is an anonymous function - that means the function which does not have any name.
Implementing reduce() with lambda function
Give a list of numbers and we have to find their sum using lambda and reduce() function.
Approach 1: Using normal way
# function to find sum of the elements
def add(data):
s=0
for n in data:
s=s+n
return s
# list of the values
fibo=[0,1,1,2,3,5,8,13,21,34,55]
print("Orignal List :",fibo)
# function call
s=add(fibo)
print("Sum = ",s)
Output
Orignal List : [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
Sum = 143
Approach 2: Using reduce() with lambda
from functools import reduce
def add(data):
s=0
for n in data:
s=s+n
return s
# list of integers
fibo=[0,1,1,2,3,5,8,13,21,34,55]
print("Orignal List :",fibo)
# using reduce and lambda
s=reduce(lambda a,b:a+b,fibo)
print("Sum = ",s)
Output
Orignal List : [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
Sum = 143