AppDividend
Latest Code Tutorials

How to Use Python Map Lambda

0

The lambda function in Python is also called an anonymous function. What do we mean by anonymous function in Python? Well, an anonymous function means that a function is without a name. To define a lambda function in Python, use the lambda keyword just like the def keyword to define a regular function.

Syntax of lambda

Syntax: lambda arguments: expression

Example using the def keyword

def sqr(x):
    return x*x

# Calling the sqr() function
print(sqr(5))

Output

25

Using the def keyword, we have defined a function with a name sqr and had to pass a value to it. After its execution, we need to return the result from where the function was called using the return keyword.

It will return the squared value of input value. See the following code snippet of a simple function.

Example using lambda keyword

lambda_sqr = lambda x: x*x

#Using the lambda function
print(lambda_sqr(5))

Output

25

And we get the same output as a simple function, but it is defined in one line only.

Lambda function’s definition does not include a “return” statement, and it always includes the returned expression. We can also put the lambda definition anywhere a function is expected, and we don’t need to assign it to a variable at all.

Python Map Lambda

Python map() is an inbuilt function that takes a lambda function and applies that function to all the elements of specified iterable and returns map objects.

Let’s define a list using [ ] as an iterable object and then use the map() and lambda function.

data = [19, 21, 18, 46, 11]

Now, use the map() and lambda function to transform the list into a Python object. Then use the list() function to convert the object into a list.

data = [19, 21, 18, 46, 11]
convo_obj = map(lambda x: x*x, data)
list_obj = list(convo_obj)
print(list_obj)

Output

[361, 441, 324, 2116, 121]

The map functions expect a function object and any number of iterables, such as the list, dictionary, etc.

The map() function executes the function_object for each element in the sequence and returns the map object.

That is it for the Python map lambda tutorial.

See also

Python map list

Python filter

Python JSON to Dict

Python List count

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.