Python 3-Lambda

Lambda Expression

Lambda Expression is also called Anonymous Expression. The function can have number of arguments but only one expression, which is evaluated and returned.

Example:

var = lambda a:a*a
print(var(5))

Output:

25

Lambda Function:

The power of lambda is better shown when you use them as an anonymous function inside another function.

Say you have a function definition which takes one argument, and that argument will be multiplied with an unknown number, this could be achieved by lambda function.

Example:

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

Output:

33

Sometimes, we can use the same function definition to make different functions, in the same program.

Example:

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

Output:

22
33