Python Funciones Lambda con EJEMPLOS

โšก Resumen inteligente

Lambda functions in Python are small anonymous functions defined with the lambda keyword instead of def. They hold a single expression, take any number of arguments, and are often passed directly to built-ins such as map(), filter(), and sorted().

  • ๐Ÿ”‘ Lambda keyword: A lambda is written as lambda arguments: expression, with no def, no name, and no explicit return statement.
  • ๐Ÿงฎ Single expression: The body holds exactly one expression whose value is returned automatically, so statements and multiple lines are not allowed.
  • ๐Ÿ”— Built-in pairing: Lambdas are commonly passed to map(), filter(), reduce(), and sorted() to transform or select items in a sequence.
  • โšก IIFE: A lambda can be defined and called immediately using the pattern (lambda x: x + x)(2), returning a result at once.
  • ๐Ÿ‡ง๐Ÿ‡ท Versus def: Regular functions need a name and can hold many statements, while lambdas trade that power for compact, one-line syntax.
  • ๐Ÿค– Asistencia de IA: AI assistants such as GitHub Copilot generate lambda expressions for map, filter, and sort keys from a short prompt.

Python Funciones lambda

ยฟEn quรฉ consiste la funciรณn Lambda? Python?

A Funciรณn Lambda en Python La programaciรณn es una funciรณn anรณnima o una funciรณn que no tiene nombre. Es una funciรณn pequeรฑa y restringida que no tiene mรกs de una lรญnea. Al igual que una funciรณn normal, una funciรณn Lambda puede tener varios argumentos con una expresiรณn.

In Python, las expresiones lambda (o formas lambda) se utilizan para construir funciones anรณnimas. Para ello utilizarรก el lambda palabra clave (tal como la usas def para definir funciones normales). Cada funciรณn anรณnima que definas en Python tendrรก 3 partes esenciales:

  • La palabra clave lambda.
  • Los parรกmetros (o variables vinculadas), y
  • El cuerpo funcional.

Una funciรณn lambda puede tener cualquier nรบmero de parรกmetros, pero el cuerpo de la funciรณn solo puede contener uno expresiรณn. Ademรกs, una lambda se escribe en una sola lรญnea de cรณdigo y tambiรฉn se puede invocar inmediatamente. Verรก todo esto en acciรณn en los prรณximos ejemplos.

Sintaxis y ejemplos

La sintaxis formal para escribir una funciรณn lambda es la siguiente:

lambda p1, p2: expression

Aquรญ, p1 y p2 son los parรกmetros que se pasan a la funciรณn lambda. Puede agregar tantos o pocos parรกmetros como necesite.

However, notice that we do not use brackets around the parameters as we do with regular functions. The last part (expression) is any valid Python expression that operates on the parameters you provide to the function.

Ejemplo

Ahora que ya conoces las lambdas, probรฉmoslo con un ejemplo. Entonces, abre tu IDLE y escribe lo siguiente:

adder = lambda x, y: x + y
print (adder (1, 2))

Code Explicaciรณn

Aquรญ, definimos una variable que contendrรก el resultado devuelto por la funciรณn lambda.

1. La palabra clave lambda utilizada para definir una funciรณn anรณnima.

2. xey son los parรกmetros que pasamos a la funciรณn lambda.

3. Este es el cuerpo de la funciรณn, que agrega los 2 parรกmetros que pasamos. Observe que es una expresiรณn รบnica. No se pueden escribir varias declaraciones en el cuerpo de una funciรณn lambda.

4. Llamamos a la funciรณn e imprimimos el valor devuelto.

Ejemplo

That was a basic example to understand the fundamentals and syntax of lambda. Let us now try to print out a lambda and see the result. Again, open your IDLE y escribe lo siguiente:

#What a lambda returns
string='some kind of a useless lambda'
print(lambda string : print(string))

Ahora guarde su archivo y presione F5 para ejecutar el programa. Este es el resultado que deberรญa obtener.

Salida:

<function <lambda> at 0x00000185C3BF81E0>

What is happening here? Let us look at the code to understand further.

Code Explicaciรณn:

1. Here, we define a cadena that you will pass as a parameter to the lambda.

2. We declare a lambda that calls a print statement and prints the result.

But why does the program not print the string we pass? This is because the lambda itself returns a function object. In this example, the lambda is not being , que son by the print function but is simply volver the function object and the memory location where it is stored. That is what gets printed at the console.

Ejemplo

Sin embargo, si escribes un programa como este:

#What a lambda returns #2
x="some kind of a useless lambda"
(lambda x : print(x))(x)

And run it by hitting F5, you will see an output like this.

Salida:

some kind of a useless lambda

Now, the lambda is being called, and the string we pass gets printed at the console. But what is that weird syntax, and why is the lambda definition covered in brackets? Let us understand that now.

Code Explicaciรณn:

1. Here is the same string we defined in the previous example.

2. In this part, we are defining a lambda and calling it immediately by passing the string as an argument. This is something called an IIFE, and you will learn more about it in the upcoming sections of this tutorial.

Ejemplo

Let us look at a final example to understand how lambdas and regular functions are executed. So, open your IDLE y en un nuevo archivo escribe lo siguiente:

#A REGULAR FUNCTION
def guru( funct, *args ):
funct( *args )
def printer_one( arg ):
return print (arg)
def printer_two( arg ):
print(arg)
#CALL A REGULAR FUNCTION 
guru( printer_one, 'printer 1 REGULAR CALL' )
guru( printer_two, 'printer 2 REGULAR CALL \n' )
#CALL A REGULAR FUNCTION THRU A LAMBDA
guru(lambda: printer_one('printer 1 LAMBDA CALL'))
guru(lambda: printer_two('printer 2 LAMBDA CALL'))

Now, save the file and hit F5 to run the program. If you did not make any mistakes, the output should be something like this.

Salida:

printer 1 REGULAR CALL

printer 2 REGULAR CALL

printer 1 LAMBDA CALL

printer 2 LAMBDA CALL

Code Explicaciรณn:

1. A function called guru that takes another function as the first parameter and any other arguments following it.

2. printer_one is a simple function which prints the parameter passed to it and returns it.

3. printer_two is similar to printer_one but without the return statement.

4. In this part, we are calling the guru function and passing the printer functions and a string as parameters.

5. This is the syntax to achieve the fourth step (i.e., calling the guru function) but using lambdas.

En la siguiente secciรณn, aprenderรก cรณmo utilizar funciones lambda con mapa(), reducir(), y filtrar() in Python.

Usando lambdas con Python incorporados

Las funciones Lambda proporcionan una forma elegante y poderosa de realizar operaciones utilizando mรฉtodos integrados en Python. Es posible porque las lambdas pueden invocarse inmediatamente y pasarse como argumento a estas funciones.

IIFE en Python lambda

IFE son las siglas de Invocรณ inmediatamente la ejecuciรณn de la funciรณn. It means that a lambda function is callable as soon as it is defined. Let us understand this with an example; fire up your IDLE y escribe lo siguiente:

 (lambda x: x + x)(2)

Aquรญ estรก el resultado y la explicaciรณn del cรณdigo:

Esta capacidad de las lambdas para ser invocadas inmediatamente le permite usarlas dentro de funciones como map() y reduce(). Es รบtil porque es posible que no desee volver a utilizar estas funciones.

lambdas en filtro()

La funciรณn de filtro se utiliza para seleccionar algunos elementos particulares de una secuencia de elementos. La secuencia puede ser cualquier iterador como listas, conjuntos, tuplas, etc.

The elements which will be selected are based on some pre-defined constraint. It takes 2 parameters:

  • Una funciรณn que define la restricciรณn de filtrado.
  • Una secuencia (cualquier iterador como listas, tuplas, etc.)

Por ejemplo,

sequences = [10,2,8,7,5,4,3,11,0, 1]
filtered_result = filter (lambda x: x > 4, sequences) 
print(list(filtered_result))

Aquรญ estรก el resultado:

[10, 8, 7, 5, 11]

Code Explicaciรณn:

1. En la primera declaraciรณn, definimos una lista llamada secuencias que contiene algunos nรบmeros.

2. Aquรญ, declaramos una variable llamada filtered_result, que almacenarรก los valores filtrados devueltos por la funciรณn filter().

3. Una funciรณn lambda que se ejecuta en cada elemento de la lista y devuelve verdadero si es mayor que 4.

4. Imprime el resultado devuelto por la funciรณn de filtro.

lambdas en el mapa()

The map function is used to apply a particular operation to every element in a sequence. Like filter(), it also takes 2 parameters:

  1. A function that defines the operation to perform on the elements
  2. Una o mรกs secuencias

Por ejemplo, aquรญ hay un programa que imprime los cuadrados de los nรบmeros en una lista dada:

sequences = [10,2,8,7,5,4,3,11,0, 1]
filtered_result = map (lambda x: x*x, sequences) 
print(list(filtered_result))

Salida:

 [100, 4, 64, 49, 25, 16, 9, 121, 0, 1]

Code Explicaciรณn:

1. Here, we define a list called sequences which contains some numbers.

2. We declare a variable called filtered_result which will store the mapped values.

3. A lambda function which runs on each element of the list and returns the square of that number.

4. Print the result returned by the map function.

lambdas en reducir()

La funciรณn reduce, al igual que map(), se utiliza para aplicar una operaciรณn a cada elemento de una secuencia. Sin embargo, difiere de map en su funcionamiento. Estos son los pasos que sigue la funciรณn reduce() para calcular un resultado:

Paso 1) Realizar la operaciรณn definida en los 2 primeros elementos de la secuencia.

Paso 2) Save this result.

Paso 3) Realizar la operaciรณn con el resultado guardado y el siguiente elemento de la secuencia.

Paso 4) Repita hasta que no queden mรกs elementos.

Tambiรฉn toma dos parรกmetros:

  1. Una funciรณn que define la operaciรณn a realizar
  2. Una secuencia (cualquier iterador como listas, tuplas, etc.)

Por ejemplo, aquรญ hay un programa que devuelve el producto de todos los elementos de una lista:

from functools import reduce
sequences = [1,2,3,4,5]
product = reduce (lambda x, y: x*y, sequences)
print(product)

Aquรญ estรก el resultado:

120

Code Explicaciรณn:

1. Import reduce from the functools module.

2. Here, we define a list called sequences which contains some numbers.

3. We declare a variable called product which will store the reduced value.

4. A lambda function that runs on each element of the list. It will return the product of that number as per the previous result.

5. Print the result returned by the reduce function.

ยฟPor quรฉ (y por quรฉ no) utilizar funciones lambda?

Como verรก en la siguiente secciรณn, las lambdas se tratan de la misma manera que las funciones regulares a nivel de intรฉrprete. En cierto modo, se podrรญa decir que las lambdas proporcionan una sintaxis compacta para escribir funciones que devuelven una รบnica expresiรณn.

However, you should know when it is a good idea to use lambdas and when to avoid them. In this section, you will learn some of the design principles used by Python developers when writing lambdas.

One of the most common use cases for lambdas is in functional programming, as Python admite un paradigma (o estilo) de programaciรณn conocido como programaciรณn funcional.

It allows you to provide a function as a parameter to another function (for example, in map, filter, etc.). In such cases, using lambdas offers an elegant way to create a one-time function and pass it as the parameter.

ยฟCuรกndo no deberรญas usar Lambda?

Nunca debe escribir funciones lambda complicadas en un entorno de producciรณn. Serรก muy difรญcil para los programadores que mantienen su cรณdigo descifrarlo. Si crea expresiones complejas de una sola lรญnea, serรญa una prรกctica mucho mejor definir una funciรณn adecuada. Como prรกctica recomendada, debe recordar que el cรณdigo simple siempre es mejor que el cรณdigo complejo.

Lambdas frente a funciones regulares

As previously stated, lambdas are just functions which do not have an identifier bound to them. In simpler words, they are functions with no names (hence, anonymous). Here is a table to illustrate the difference between lambdas and regular functions in Python.

lambdas Funciones regulares
Sintaxis:

lambda x : x + x
Sintaxis:

def (x) :
return x + x 
Las funciones lambda sรณlo pueden tener una expresiรณn en su cuerpo. Las funciones regulares pueden tener mรบltiples expresiones y declaraciones en su cuerpo.
Lambdas do not have a name associated with them. That is why they are also known as anonymous functions. Las funciones regulares deben tener nombre y firma.
Lambdas no contienen una declaraciรณn de devoluciรณn porque el cuerpo se devuelve automรกticamente. Functions which need to return a value should include a return statement.

Explicaciรณn de las diferencias.

La principal diferencia entre una funciรณn lambda y una funciรณn regular es que la funciรณn lambda evalรบa solo una expresiรณn y genera un objeto de funciรณn. En consecuencia, podemos nombrar el resultado de la funciรณn lambda y usarlo en nuestro programa como lo hicimos en el ejemplo anterior.

Una funciรณn normal para el ejemplo anterior se verรญa asรญ:

def adder (x, y):
return x + y 
print (adder (1, 2))

Aquรญ tenemos que definir un nombre para la funciรณn que devoluciones el resultado cuando nosotros Llame it. A lambda function does not contain a return statement because it will have only a single expression which is always returned by default. You do not even have to assign a lambda either, as it can be immediately invoked (see the previous section). As you will see, lambdas become particularly powerful when we use them with PythonFunciones integradas.

Sin embargo, es posible que todavรญa te preguntes en quรฉ se diferencian las lambdas de una funciรณn que devuelve una sola expresiรณn (como la anterior). A nivel de intรฉrprete no hay mucha diferencia. Puede parecer sorprendente, pero cualquier funciรณn lambda que defina en Python es tratada como una funciรณn normal por el intรฉrprete.

At the bytecode level, the two definitions are handled in the same way by the Python interpreter. Now, you cannot name a function lambda porque estรก reservado por Python, but any other function name will yield the same bytecode.

Preguntas Frecuentes

Yes. A lambda can use a conditional expression such as lambda x: โ€˜evenโ€™ if x % 2 == 0 else โ€˜oddโ€™. It cannot hold a full if statement, because the body of a lambda must be a single expression rather than a block of statements.

Generally no. PEP 8 recommends using def when a function needs a name, because binding a lambda to a variable gives it a name yet loses the clearer traceback that def provides. Lambdas are best passed directly to functions such as sorted(), map(), or filter().

No. At the bytecode level Python treats a lambda and an equivalent def the same way, so there is no speed advantage. A lambda only saves a line of code; it does not execute faster than a named function doing identical work.

Yes. A lambda can read variables from the enclosing scope, forming a closure. Inside a loop, be careful: the lambda captures the variable itself, not its current value, so use a default argument like lambda x, n=n: x + n to freeze it.

Pass a lambda as the key argument to sorted() or list.sort(). For example, sorted(users, key=lambda u: u[โ€˜ageโ€™]) orders items by age. The lambda tells Python which value to compare for each element, giving concise custom sorting without a separate named function.

Not directly, because an anonymous lambda has no name to reference. You can work around this by assigning the lambda to a variable and calling that name, but a normal def function is the clearer and recommended choice for recursion.

Lambdas power quick, inline transformations in AI and machine learning code. Data scientists pass them to pandas .apply(), map(), and filter() to clean or reshape data, and as key functions for sorting features, keeping preprocessing compact inside larger training pipelines.

GitHub Copilot suggests complete lambda expressions from a short comment or the surrounding code, including the correct parameters and expression for map(), filter(), or sorted() calls. It can also propose converting a verbose lambda into a clearer named function when readability matters.

Resumir este post con: