Home » Python

Python | Lambda and map() with Example

Python lambda and map() with Example: Here, we are going to learn how to use map() with lambda in python?
Submitted by Pankaj Singh, on October 12, 2018

The map() function is used to apply the function to all items of an iterable collection like list, tuple etc and it returns the list of the result after performing the functionality defined in the applied function.

Example:

Given a list of temperatures and we have to convert 1) all the values in Celsius and 2) all the values in Fahrenheit - using map() with lambda.

1) Approach 1: Using normal way

# function definition to convert temp. from c to f
def ctof(c):
    f=9/5*c+32
    return f

# function definition to convert temp. from f to c
def ftoc(f):
    c=5/9*(f-32)
    return c

# list of the values	
temp=[12,45,6,78,5,26,67]
print("Orignal Data   : ",temp)

# list declration to store temp. in C
cel=[]
for t in temp:
    x=ftoc(t)
    cel.append(x)
print("Celcuis Data   : ",cel)

# list declration to store temp. in F
far=[]
for t in temp:
    x=ctof(t)
    far.append(x)
print("Farenhiet Data : ",far)

Output

Orignal Data   :  [12, 45, 6, 78, 5, 26, 67]
Celcuis Data   :  [-11.11111111111111, 7.222222222222222, -14.444444444444445, 
25.555555555555557, -15.0, -3.3333333333333335, 19.444444444444446]
Farenhiet Data :  [53.6, 113.0, 42.8, 172.4, 41.0, 
78.80000000000001, 152.60000000000002]

2) Approach 2: Using map() with lambda

# list of the values
temp=[12,45,6,78,5,26,67]
print("Orignal Data   : ",temp)

# converting values to cel using map and lambda
cel=list(map(lambda f:5/9*(f-32),temp))
print("Celcuis Data   : ",cel)

# converting values to far using map and lambda
far=list(map(lambda c:9/5*c+32,temp))
print("Farenhiet Data : ",far)

Output

Orignal Data   :  [12, 45, 6, 78, 5, 26, 67]
Celcuis Data   :  [-11.11111111111111, 7.222222222222222, -14.444444444444445, 
25.555555555555557, -15.0, -3.3333333333333335, 19.444444444444446]
Farenhiet Data :  [53.6, 113.0, 42.8, 172.4, 41.0, 
78.80000000000001, 152.60000000000002]





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL







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.