In python , lambda functions are also known as one line function or anonymous function as they are defined with no name. Using lambda functions reduce number of lines in the code and also the execution speed of your code becomes very faster. In the below example we will see the simple example of the lambda. But before that lets see the basic syntax of the lambda functions:
lambda arguments: expression
It can accept any number of arguments but only one expression that can be evaluated. The lambda function doesn't contain any return statement and by default it will return the value. Since functions are also objects in python, you need to store them in the variables. The following is the simple example to find the cube of a number using the concept of lambda.
a = lambda b:pow(b,3)
print(a(5))
The output of this program will be:
Lets see another example that consists of a two arguments and that finds the power of first number to the second number.
a = lambda b,c:pow(b,c)
print(a(5,4))
The final output on execution will be:
Now you may have written a program that shows whether a given number is even or odd using function. Although the program is simple, it typically includes significant lines of code. Lets see how lambda can be used to write such programs.
a = lambda b:"Even number" if b%2==0 else "Odd Number"
print(a(7))
The output of this code is: