reduce() with lambda in python by R4R Team

Lambda-

-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

reduce()-

-reduce() is a python function which apply on the particular function to manipulate the given sequence.
-It is defined in functools module.

Syntax-

functools.reduce(function,sequence)


program-

#import the functools module
import functools

#take input of the list
print("Enter number in list")
n=map(int,input().split())

x=functools.reduce(lambda x,y:x+y,n)
print("Sum of list is :",x)


output-

Enter number in list
1 2 3 4
Sum of list is : 10


-In this program, we take an input of the list, then instead of making a function and pass in reduce, we directly make a lambda function which take two values and return their addition.




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!