Python – Lambda Functions
What if you don’t mention the function name, did you do that if you don’t mention a name of function it becomes anonymous function automatically. Function without name is called anonymous function. And you can also call them as lambda function.
In case you wish to make your function more concise, easy to write and read, you can create Lambda functions. You can use Lambda function when you require nameless function for short period of time.
A lambda function can take any number of arguments but can only have one expression.
Anonymous lambda function can be defined using the keyword lambda.
Lambda functions can not contain commands, and they can not contain more than one expression.
syntax: lambda arguments: expression
Lambda function can take any number of arguments (including optional arguments) and returns the value of a single expression.
Let’s take an example to understand.
x = (lambda a:a*4) print(x(5)) #OUTPUT 20
While the normal function are defined using def keyword, in Python anonymous functions are defined using the lambda function.
Let’s say if you want to define a function which will add two numbers, you can do that using Lambda function:
f = (lambda a,b:a+b) print(f(2,20)) #OUTPUT 22