Python Lambda

Python Lambda


A lambda is a modest anonymous function.

A lambda can only take a single expression and use a number of arguments.

Syntax:-

lambda arguments : expression

The expression is run and the result will be returned :

Example 1 :- Add 10 to argument a, and return the result :

x = lambda a: a + 10
print(x(5))

Output :-

15

The functions of Lambda can take any number of arguments :

Example 2 :- Multiply argument a and return the outcome with argument b :

x = lambda a, b: a * b
print(x(5, 6))

Output :-

30

Example 3 :- Resume the arguments a, b, and c and return them :

x = lambda a, b, c: a + b + c
print(x(5, 6, 2))

Output :-

13



You can also search for these topics, python lambda function, example for python lambda, how to apply the lambda in python, define python lambda condition, how to capture python lambda, The definition used for lambda using python, lambda keyword in python, syntax for lambda in python.

Why Use Lambda Functions?

When used as an anonymous function within another function, the power of lambda is best demonstrated.

Say, you have an argument definition for the function, and this argument is multiplied by an unknown number :

def myfunc(n):
  return lambda a : a * n

Example 1 :- Use this function definition to create a function which always doubles the send number :

def myfunc(n):
  return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))

Output :-

22

Example 2 :- Use the same concept in order to create a function that triples your number :

def myfunc(n):
  return lambda a : a * n
mytripler = myfunc(3)
print(mytripler(11))

Output :-

33

Example 3 :- To perform both functions in the same program to use the same function definition :

def myfunc(n):
  return lambda a : a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11)) 
print(mytripler(11))

Output :-

22
33

When an anonymous function is needed for a brief length of time, use lambda functions.



You can also search for these topics, python why use lambda function apply, Why Use Lambda Functions before definition, Why python Use Lambda Functions condition, difference between python Use Lambda Functions, example for Use Lambda Functions in python, how to replace the Use Lambda Functions using python.