Home »
Python
Python reduce() with Lambda Function
Python reduce() with lambda function: In this tutorial, we will learn how to use the reduce() function with lambda function.
By Pankaj Singh Last updated : December 30, 2023
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
Python Tutorial