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





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.