Lambda functions are throw-away functions, i.e., they are just needed; they have been created and can be used anywhere a function is required.
Lambda functions are so-called because they are not declared as other functions using the keyword def. They are created using the lambda keyword.
The syntax of the lambda function is given below:
lambda arguments: expression
The arguments contain a comma-separated list of arguments, and the expression is an arithmetic expression that uses these arguments. The function can be assigned to a variable to give it a name.
Lambda function contains the following features:
- Lambda function has no name.
- Lambda functions can take any number of arguments.
- Lambda function definition does not have an explicit return statement, but it always contains an expression that is returned.
- They cannot access variables other than those in their parameter list.
- Lambda function cannot even access global variables.
- We can pass lambda functions as arguments in other functions.
- We can pass lambda arguments to a function.
- We can define a lambda that receives no arguments but simply returns an expression.
sum=lambda x, y:x+y print("Sum=",sum(10,20))
def min(a,b): if(a<b): return(a) else: return(b) sum=lambda x,y:x+y # lambda function to add two numbers sub=lambda x,y:x-y # lambda function to subtract two numbers print("smaller of two numbers=",min(sum(-6,-8),sub(-1,2))) # pass lambda functions as arguments
smaller of two numbers= -14
def f1(f,n): print(f(n)) twice=lambda x:x*2 thrice=lambda x:x*3 f1(twice,4) f1(thrice,3)