How to use lambda() Function with map() In Python

The map() function in Python takes in a function and a list as an argument. The function is called with a lambda function and a list and a new list is returned which contains all the lambda-modified items returned by that function for each item. Example: 

Multiply all elements of a list by 2 using lambda and map() function

The code doubles each element in a list using a lambda function and the map' function. It then prints the new list with the doubled elements. The output displays each element from the original list, multiplied by 2.

Python3




li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61]
 
final_list = list(map(lambda x: x*2, li))
print(final_list)


Output:

[10, 14, 44, 194, 108, 124, 154, 46, 146, 122]

Transform all elements of a list to upper case using lambda and map() function

The code converts a list of animal names to uppercase using a lambda function and the map' function. It then prints the list with the animal names in uppercase. The output displays the animal names in all uppercase letters.

Python3




animals = ['dog', 'cat', 'parrot', 'rabbit']
uppered_animals = list(map(lambda animal: animal.upper(), animals))
 
print(uppered_animals)


Output:

['DOG', 'CAT', 'PARROT', 'RABBIT']

Python Lambda Functions

Python Lambda Functions are anonymous functions means that the function is without a name. As we already know the def keyword is used to define a normal function in Python. Similarly, the lambda keyword is used to define an anonymous function in Python

Similar Reads

Python Lambda Function Syntax

Syntax: lambda arguments : expression This function can have any number of arguments but only one expression, which is evaluated and returned. One is free to use lambda functions wherever function objects are required. You need to keep in your knowledge that lambda functions are syntactically restricted to a single expression. It has various uses in particular fields of programming, besides other types of expressions in functions....

Python Lambda Function Example

In the example, we defined a lambda function(upper) to convert a string to its upper case using upper()....

Use of Lambda Function in Python

...

Practical Uses of Python lambda function

Let’s see some of the practical uses of the Python lambda function....

Using lambda() Function with filter()

...

Using lambda() Function with map()

...

Using lambda() Function with reduce()

Python Lambda Function with List Comprehension...

Contact Us