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. By Shivang Yadav Last updated : September 17, 2023

Lambda functions

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.

Problem statement

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.

Examples for applying lambda functions on array

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

Example 1: Apply lambda functions on array

Here, we are writing a 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

The output of the above program is:

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]

Example 2: Apply lambda functions on array

Here, we are writing a 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

The output of the above program is:

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 »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.