What Is Lambda Function in Python?
What Is Lambda Function in Python?
• Notice, there can be any number of arguments but can contain only a
single expression
• There is no return statement
Need for Lambda Functions
Let’s try to define a function for calculating the squares of given values.
# calculate squares using lambda
Let’s also look at how to do the same function using def keyword, and
compare them.
def squares_def(x):
return x*x
print('Using def: ', squares_def(5))
Lambda functions can have 0 or 1 expression, not more.
1. No expression : contains no expression, will give the same output for all arguments.
Example:
x = lambda : "hello Raj Welcome to Python Programming Language"
print(x())
2. Single expression: They can contain either one expression or no expression. We cannot put more
than one expression in a lambda function.
Example:
You can implement a lambda function without using a variable name. You can
also directly pass the argument values into the
Lambda function . This cannot be done using def function
Lambda function supports all kinds of arguments just like the normal
Example :
1. Keyword Arguments:
2. Variable list of Arguments
3. Positional arguments:
Lambda functions accept all kinds of arguments
like normal def function
## Named Arguments ##
## Variable Arguments ##
## Positional arguments ##
x = lambda a : a + 10
print(x(5))
O/P – 15
LAMBDA Function in Python
• Lambda functions can take any number of arguments:
but have only one expressions.
Example - Multiply argument a with argument b
x = lambda a, b: a * b
print(x(5, 6)
LAMBDA Function in Python
• Lambda functions can take any number of arguments
but have only one expressions.
x = lambda a, b: a * b
print(x(5, 6)
O/P - 30
LAMBDA Function in Python
Example -2 - Summarize argument a,b and c and return
the result.
x = lambda a, b, c: a + b + c
print(x(5, 6, 2))
O/P = 13
LAMBDA Function in Python
Example -2 - Summarize argument a,b and c and return
the result.
x = lambda a, b, c: a + b + c
print(x(5, 6, 2))
O/P = 13
LAMBDA Function in Python
Example -2 - Summarize argument a,b and c and return
the result.
x = lambda a, b, c: a + b + c
print(x(5, 6, 2))
O/P = 13