The Python lambda function allows the creation of an anonymous function that has no names using a facility. In Python, the lambda functions are small functions that are usually no more than a line and can have multiple arguments like a normal function. The lambda function only consists of one function and is very small. When the lambda function is applied to an argument, the result returns the values of an expression and no return statement is needed.
Python lambda Function
The lambda function is simple and requires the keyword lambda followed by a minimum of one argument and if multiple arguments, separated by a comma, followed by a colon, and a single line expression.
The below two examples produce the same output, but the lambda function is a bit more concise and easier code to review (in my opinion).
def() Example
Input:
1 2 3 4 | def addition(x, y): print(x + y) addition(20, 10) |
Output:
1 | 30 |
lambda function Example:
Input:
1 2 3 | lambda_addition = lambda x, y: x + y print(lambda_addition(20, 10)) |
Output:
1 | 30 |
But Why Use Lambda Functions?
The Python lambda function can be powerful when using the function anonymously in a function, within another function. We can use the def() from the previous example that will take an argument, and we can use that argument and add with another number that will be unknown.
Input:
1 2 3 4 5 6 | def power_lambda(n): return lambda x : x * n multiple_10 = power_lambda(10) print(multiple_10(5)) |
Output:
1 | 50 |