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.
Contact Us