add two list with the help of lambda and map() by R4R Team

lambda function-
-In Python, anonymous function means that a function is without a name. As we already know that def keyword is used to define the normal functions and the lambda keyword is used to create anonymous functions.

Syntax-
lambda argument:expression

map() function-
-It is a python function which returns a list of the results after applying the given function to each item of a given iterable like list,tuple.

Syntax-
map(fun,iter)

Lambda with map function-
In map we require a function for argument, so at the place of the function, we create a lambda function.

Syntax-
map(lambda arg:exp,iter)

-Here we want to add two list with the help of the these two functions

Example-

list1 is [1,1,1,1]
list2 is [2,2,2,2]
sum is [3,3,3,3]


program-

print("Enter element in the first list")
l1=list(map(int,input().split()))
print("Enter element in the second list")
l2=list(map(int,input().split()))

print("List one is",l1)
print("List two is",l2)
#code for add two list with the help of map and lambda
add=map(lambda x,y:x+y,l1,l2)
print("After addition list become")
print(list(add))


output-

Enter element in the first list
1 2 3 4
Enter element in the second list
4 3 2 1
List one is [1, 2, 3, 4]
List two is [4, 3, 2, 1]
After addition list become
[5, 5, 5, 5]

Enter element in the first list
1 1 1 1 1 1
Enter element in the second list
1
List one is [1, 1, 1, 1, 1, 1]
List two is [1]
After addition list become
[2]


-In this program, we take a input of two list and using map(int,input().split()) we take input of integer value, then lambda x,y:x+y take two argument, one from list1 and another from list2. add add both number and return to add variable, at the last we print that resultant list.
-In the second output, we pass two list of unequal length and try to add them, then it only add upto small length list.




Leave a Comment:
Search
Categories
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!