Python Lambda Functions

Table of Contents

What is Lambda expression ?

Anonymous functions are the function which are created without a name
In Python, small anonymous functions can be created with the lambda keyword containing one expression
They are syntactically restricted to a single expression so they are called as lambda expression also.
It is used primarily to write very short functions

Syntax of lambda function

Lambda function has the following syntax

lambda arguments : expression

Examples of lambda functions

For example we have a function add() to add two values passed as arguments to it as follows
General function

def add(x, y):
    return x + y

print(add(5, 6)) # calling function, prints 11

The above function can be written in a single line using lambda expression

add = lambda x, y: x + y
print(add(5, 6)) # calling function, prints 11

lambda x, y: x + y is the lambda function/expression. x, y are the arguments passed to it. x + y is the expression that is evaluated and automatically returned.
So the lambda expression creates a function object and does not have a name. We are assigning that to a name add and using the name add we are calling the lambda function as add(5, 6)
More Examples
Example 1
Lambda functions can be directly called without a

print((lambda x, y: x + y)(5, 6)) # calling function, prints 11

Example 2

print((lambda x: x ** 2)(2)) # prints 4
print((lambda x: x ** 2)(3)) # prints 9
print((lambda x: x ** 2)(5)) # prints 25
Click any Link
to navigate to certain page easily
Write a line to us
Your Email
Title
Description