Lambda function or anonymous function
Lambda function or anonymous function
What is lambda function?
Lambda function is a function they are not declared as other function using def keyword.Rather they are created using lambda keyword.
Syntax:
lambda argument:Expression
Example:
sum=lambda x,y :x+y
print(sum(7,5))
#in the above code lambda function return the value of sum.
#in lambda function x,y:x+y (x,y is agreement and x+y is expression that
#get evaluate and return)
#it return function object which assign to the identifier sum.
lambda function have no name.
lambda function can take any number of argument.
They are one line argument and hence can not contain multiple line.
lambda function can not even access global variable.
lambda function with ordinary function
def increment(y):
return(lambda x:x+1)(y)
# in ordinary function return lambda function.#in lambda function x is argument,x+1 is expression
#and y is assign argument/passing argument
a=100
print("a=",a)
b=increment(a)
print(b)
def function(f,n,m):
print(f(n,m))
#function(f,n,m):(takes three argument f=lambda function pass as argument,)
#(n,m= first and second argument of lambda function)
sum=lambda x,y:x+y
function(sum,10,5)
#in the above code lambda function return the value of sum.
#in lambda function x,y:x+y (x,y is agreement and x+y is
# expression that get evaluate and return)
#it return function object which assign to the identifier sum.
Q.program to print sum of n natural number using lambda function.
x=lambda:sum(range(1,n+1))
n=int(input("Enter the value of N :"))
print("Total sum=",x())
Q.program to check greater number between 3 numbers.
x=lambda a,b,c:a if a>b and a>c else b if b>c else c
a=int(input("Enter 1st number :"))
b=int(input("Enter 2nd number :"))
c=int(input("Enter 3rd number :"))
print("Greater number is :",x(a,b,c))
Enter 1st number :12
Enter 2nd number :14
Enter 3rd number :11
Greater number is : 14
Thank you..........
please like and follow my facebook page.....
Let's_code
Decision making statement in python
Lopping_statement_in_python
Pattern program
Comments
Post a Comment