Site icon DataFlair

Python Program on Lambda with Map Function

Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python

In this article, we will explore a Python program that employs the map function in combination with a lambda function. The map function is a built-in Python function that applies a specified function to all items in an input list and returns an iterable (often a list) of the results. The program showcases the use of map and a lambda function to calculate the square of each element in a given list.

Prerequisites

Topic Explanation

This program begins by creating a list called mylist containing numeric values. It proceeds to leverage the map function in conjunction with a lambda function to calculate the square of each element in mylist. These squared values are stored in a new list, mylist1, and subsequently displayed.

Through this approach, the program effectively demonstrates how the map function, combined with lambda functions, simplifies mathematical operations on lists. Readers gain insight into utilizing these tools for efficient data transformations, enhancing their proficiency in Python programming.

Program Code:

# Program for Map with Lambda
# Define a list of integers
mylist = [10, 3, 20, 6, 4, 30]

# Use the map function with a lambda expression to square each element in the list
# The lambda function takes an input x and returns x squared (x*x)
mylist1 = list(map(lambda x: x*x, mylist))

# Print the resulting list containing the squared values of the original elements
print(mylist1)
Output:
[100, 9, 400, 36, 16, 900]

Code Explanation:

Summary

In conclusion, this article demonstrated the use of the map function with a lambda expression in Python. The program showcased how to square each element in a list efficiently. Readers, familiar with basic Python concepts like map and lambda functions, can easily understand and implement this approach. The provided code and its explanation serve as a straightforward example for those looking to enhance their Python skills, highlighting the practical application of these fundamental functions in real-world scenarios.

Exit mobile version