In this blog, I am going to cover the lambda function. It is a function that creates a function object using the lambda keyword. The function object lasts only as long as it's called and then disappears. It can be called by using the keyword 'lambda' following with parameters in the function and then the function body.
The syntax is
lambda arguments: expression
It can take any number of arguments, but can only have one expression. Lambda Function Example Below is a simple lambda function example.
x = lambda a, b: a + b
print(x(5,6))
Output:
11
Uses of Lambda Functions
Lambda function is better shown when they are used as an anonymous function inside another function. Let's suppose you have a function definition that takes one argument, and that argument will be powered by an unknown number:
def power(n):
return lambda a: a ** n
Use that function definition to make a function that always squares the number you send
square = power(2)
print(square(3))
Or similarly, we can generate tons of other functions from that single function such as
cube = power(3)
print(cube(3))
IVTimes = power(4)
print(IVTimes(3))