Python Lambda

Lambda functions are small anonymous functions.

Lambda functions can accept any number of arguments but can only have one expression.

Syntax

lambda arguments : expression

Execute the expression and return the result:

Example

A lambda function that adds 10 to the number passed as an argument and then prints the result:

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

Run Example

Lambda functions can accept an arbitrary number of parameters:

Example

A lambda function that multiplies parameters a and b and prints the result:

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

Run Example

Example

A lambda function that adds parameters a, b, and c and prints the result:

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

Run Example

Why Use Lambda Functions?

When you use lambda as an anonymous function inside another function, it better demonstrates the powerful capabilities of lambda.

Suppose you have a function definition with one parameter, and the parameter will be multiplied by an unknown number:

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

Use this function definition to create a function that always doubles the number sent:

Example

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

Run Example

Or, use the same function definition to create a function that always triples the number you send:

Example

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

Run Example

Or, use the same function definition in the same program to generate two functions:

Example

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

Run Example

If you need an anonymous function in a short time, please use the lambda function.