Lambda de Python

La función lambda es una pequeña función anónima.

La función lambda puede aceptar cualquier cantidad de parámetros, pero solo puede tener una expresión.

Sintaxis

lambda arguments : expression

Ejecutar la expresión y devolver el resultado:

Example

Una función lambda que suma 10 al número传入 como parámetro y luego imprime el resultado:

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

Run Example

Lambda functions can accept any 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 you send:

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.