Python program to apply lambda functions on array

Here, we will write a Python program to apply lambda function on array. We have an array with temperature in Celsius and we will convert it to data in Fahrenheit.
Submitted by Shivang Yadav, on March 19, 2021

Lambda functions in Python are special functions available in python. They are anonymous functions i.e., without any function name. 

We have seen a basic lambda function to convert Celsius to Fahrenheit.

Let's suppose a real-life scenario in which you have a website that displays the temperature of multiple cities. Here, you get data of temperature of all cities in a collection and conversion can be made easy using lambda functions.

Here are functions to convert temperature stored in an array with and without lambda expression.

Python program to convert temperature stored in an array using regular function

# Python program to convert temperature to 
# Fahrenheit using function

# Function that converts temperature to Farenhiet
def convCtoF(c):
    f=9/5*c+32
    return f

# Array storing Temperature in celsius
celsiusTemperature =[12,45,6,78,5,26,67]
print("Temperature in celsius : ",celsiusTemperature)

# Array that will store Temperature in Fahrenheit
FahrenheitTemperature = []
for t in celsiusTemperature:
    x = convCtoF(t)
    FahrenheitTemperature.append(x)
# Printing Fahrenheit Temperature 
print("Temperature in Fahrenheit : ",FahrenheitTemperature)

Output:

Temperature in celsius :  [12, 45, 6, 78, 5, 26, 67]
Temperature in Fahrenheit :  [53.6, 113.0, 42.8, 172.4, 41.0, 78.80000000000001, 152.60000000000002]

Python program to convert temperature to Fahrenheit using lambda function

# Python program to convert temperature to 
# Fahrenheit using lambda function 

# Array storing temperature in celsius
celsiusTemp = [12,45,6,78,5,26,67]
print("temperature in Celsius : ",celsiusTemp)

# Converting data to Fahrenheit using lambda function 
fahrenTemp = list(map(lambda c:9/5*c+32,celsiusTemp))
print("Temperature in Fahrenheit : ",fahrenTemp)

Output:

temperature in Celsius :  [12, 45, 6, 78, 5, 26, 67]
Temperature in Fahrenheit :  [53.6, 113.0, 42.8, 172.4, 41.0, 78.80000000000001, 152.60000000000002]

Python Array Programs » Python Lambda Function Programs »





Comments and Discussions




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.