After reading this Python lambda expression or function topic, you will understand how to implement it in Python.
Lambda expression or function is the simple, anonymous function supports by Python.
Lambda Expressions Syntax:
The syntax for Lambda expression is given below,
lambda parameter_list : expression
where:
- lambda is a Keyword written at the beginning of a lambda expression.
- parameter_list is a list of parameters separated by commas.
- expression is a single Python expression.
Note: lambda expression can take more than one parameters.
Example
Program (1): To demonstrate lambda function that multiplies 3 to the number passed as parameter and display the result.
#defining lambda expression f = lambda x: 3*x #passing 10 as parameter to lambda expression and display result print(f(10))
Output (1)
30
Let us discuss one example based on the above-stated Note as lambda expression can take more than one parameters.
Example:
Program (1): To demonstrate lambda function that multiplies two parameters named as x and y, and display the result.
#defining lambda expression f = lambda x, y: x*y #passing 10 and 20 as parameters to lambda expression and display result print(f(10,20))
Output (1)
200
Why Sometimes Lambda expression is a better choice?
Let us consider the example to describe why lambda expression is better.
Example
Program (1): To write a function in python that multiply 3 to the number passed as parameter and display the result.
def f(x): return 3*x print(f(10))
Output (1)
30
For the above program(1), the same function can be written by using the Lambda expression as
print((lambda x: 3*x)(10))
Output (1)
30
Explanation:
- Lambda expression produces the same output in an easier way.
- Here, print((lambda x: 3*x)(10)) is the only one Python statement is required, so better to go with Lambda expression for such kind of Python program.