Tuesday 30 March 2021

Lambda Function in Python


Lambda Function

Lambda function is a function, which is defined without a name (anonymous). Hence, named as anonymous function. Lambda function is defined using the keyword lambda that’s why it also called as lambda function.

Lambda functions are syntactically restricted to a single expression. However, can have multiple arguments separated with commas. Semantically, lambda functions are just syntactic sugar for a normal function definition. Lambda functions can be used wherever function objects are required.


Using lambda function

syntax- lambda args: expression

pow = lambda x: x**2


Here, x is the argument to the lambda function and x**2 is the expression which gets assigned to the variable ”pow” after evaluation. 

Notice, the lambda function has no name and doesn’t contain any parentheses unlike normal function.

The above lambda function is similar to:

def pow(x):

    return x**2