English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutorial Básica de Python

Control de flujo en Python

Funciones en Python

Tipos de datos en Python

Operaciones de archivos en Python

Objetos y Clases de Python

Fecha y Hora de Python

Conocimientos Avanzados de Python

Manual de Referencia de Python

Funciones anónimas (Lambda) en Python

En este artículo, conocerás las funciones anónimas, también conocidas como funciones lambda. A través de ejemplos, entenderás qué son, su sintaxis y cómo usarlas.

¿Qué es la función lambda en Python?

En Python, las funciones anónimas no tienen nombre definidoFunción.

Aunque 'def' se utiliza como palabra clave en Python para definir funciones normales, se utiliza la palabra clave 'lambda' para definir funciones anónimas.

Por lo tanto, las funciones anónimas también se conocen como funciones lambda.

¿Cómo se usa la función lambda en Python?

La función lambda en Python tiene la siguiente sintaxis.

Sintaxis de la función lambda en Python

lambda argumentos: expresión

La función lambda puede tener cualquier número de parámetros, pero solo puede tener una expresión. La expresión se evalúa y devuelve. La función lambda se puede usar en cualquier lugar donde se necesite un objeto de función.

Ejemplo de función lambda en Python

This is an example of a lambda function that doubles the input value.

# Program demonstrates the use of lambda functions
double = lambda x: x * 2
print(double(5))

Output result

10

In the above program, lambda x: x * 2is a lambda function. Here x is the parameter, x * 2is an expression for evaluation and return.

This function has no name. It returns a function object, which is assigned to the identifier double. Now we can call it a normal function. Below is the declaration

double = lambda x: x * 2

is equivalent to:

def double(x):
   return x * 2

Using Lambda functions in python

When we temporarily need an anonymous function, we use the lambda function.

In Python, we usually use it as an argument for higher-order functions (functions that take other functions asarguments)。Lambda functions can be used with filter(), map(), and other built-in functions.

Example of using lambda with filter()

The filter() function in Python accepts a function and a list as parameters.

The filter() function in Python calls the function for each item in the list and returns a new list containing the items for which the function calculation results in True.

This is an example of using the filter() function to filter only even numbers from the list.

# Program filters even items from the list
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(filter(lambda x: (x%2 == 0) , my_list))
print(new_list)

Output result

[4, 6, 8, 12]

Example of using lambda with map()

The map() function in Python accepts a function and a list.

The map() function in Python calls the function for each item in the list and returns a new list containing the items returned by the function for each item.

This is an example of doubling all items in the list using the map() function.

# Use map() to double each item in the list
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(map(lambda x: x * 2 , my_list))
print(new_list)

Output result

[2, 10, 8, 12, 16, 22, 6, 24]