Home »
Python
Python | Lambda and reduce() with Example
Python lambda and reduce() with Example: Here, we are going to learn how to use reduce() with lambda in Python?
Submitted by Pankaj Singh, on October 12, 2018
The reduce() function applies on each element of an iterable collection and returns the reduced (based on applied calculation through the function) value.
Example:
Give a list of numbers and we have to find their sum using lambda and reduce() function.
1) 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
2) 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
ADVERTISEMENT
ADVERTISEMENT