Python Funções Lambda com EXEMPLOS
⚡ Resumo 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().

Em que consiste a função Lambda Python?
A Função Lambda em Python programação é uma função anônima ou uma função sem nome. É uma função pequena e restrita que não possui mais de uma linha. Assim como uma função normal, uma função Lambda pode ter vários argumentos com uma expressão.
In Python, expressões lambda (ou formas lambda) são utilizadas para construir funções anônimas. Para fazer isso, você usará o lambda palavra-chave (assim como você usa def para definir funções normais). Cada função anônima que você define em Python terá 3 partes essenciais:
- A palavra-chave lambda.
- Os parâmetros (ou variáveis vinculadas) e
- O corpo da função.
Uma função lambda pode ter qualquer número de parâmetros, mas o corpo da função só pode conter um expressão. Além disso, um lambda é escrito em uma única linha de código e também pode ser invocado imediatamente. Você verá tudo isso em ação nos próximos exemplos.
Sintaxe e exemplos
A sintaxe formal para escrever uma função lambda é fornecida abaixo:
lambda p1, p2: expression
Aqui, p1 e p2 são os parâmetros que são passados para a função lambda. Você pode adicionar quantos parâmetros precisar.
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.
Exemplo 1
Agora que você sabe sobre lambdas, vamos tentar com um exemplo. Então, abra seu IDLE e digite o seguinte:
adder = lambda x, y: x + y print (adder (1, 2))
Code Explicação
Aqui, definimos uma variável que conterá o resultado retornado pela função lambda.
1. A palavra-chave lambda usada para definir uma função anônima.
2. x e y são os parâmetros que passamos para a função lambda.
3. Este é o corpo da função, que adiciona os 2 parâmetros que passamos. Observe que é uma expressão única. Você não pode escrever várias instruções no corpo de uma função lambda.
4. Chamamos a função e imprimimos o valor retornado.
Exemplo 2
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 e digite o seguinte:
#What a lambda returns string='some kind of a useless lambda' print(lambda string : print(string))
Agora salve seu arquivo e pressione F5 para executar o programa. Esta é a saída que você deve obter.
Saída:
<function <lambda> at 0x00000185C3BF81E0>
What is happening here? Let us look at the code to understand further.
Code Explicação:
1. Here, we define a corda 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 chamado by the print function but is simply voltar the function object and the memory location where it is stored. That is what gets printed at the console.
Exemplo 3
No entanto, se você escrever um 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.
Saída:
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 Explicação:
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.
Exemplo 4
Let us look at a final example to understand how lambdas and regular functions are executed. So, open your IDLE e em um novo arquivo, digite o seguinte:
#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.
Saída:
printer 1 REGULAR CALL printer 2 REGULAR CALL printer 1 LAMBDA CALL printer 2 LAMBDA CALL
Code Explicação:
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.
Na próxima seção, você aprenderá como usar funções lambda com mapa (), reduzir() e filtro() in Python.
Usando lambdas com Python embutidos
As funções lambda fornecem uma maneira elegante e poderosa de executar operações usando métodos integrados em Python. É possível porque lambdas podem ser invocadas imediatamente e passadas como argumento para essas funções.
IIFE em Python Lambda
IIFE é um anagrama para execução da função invocada imediatamente. 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 e digite o seguinte:
(lambda x: x + x)(2)
Aqui está a saída e a explicação do código:
Essa capacidade de invocar lambdas imediatamente permite que você os use dentro de funções como map() e reduzir(). É útil porque você pode não querer usar essas funções novamente.
lambdas no filtro()
A função de filtro é usada para selecionar alguns elementos específicos de uma sequência de elementos. A sequência pode ser qualquer iterador, como listas, conjuntos, tuplas, etc.
The elements which will be selected are based on some pre-defined constraint. It takes 2 parameters:
- Uma função que define a restrição de filtragem
- Uma sequência (qualquer iterador como listas, tuplas, etc.)
Por exemplo, nos
sequences = [10,2,8,7,5,4,3,11,0, 1] filtered_result = filter (lambda x: x > 4, sequences) print(list(filtered_result))
Aqui está o resultado:
[10, 8, 7, 5, 11]
Code Explicação:
1. Na primeira instrução, definimos uma lista chamada sequências que contém alguns números.
2. Aqui, declaramos uma variável chamada filtered_result, que armazenará os valores filtrados retornados pela função filter().
3. Uma função lambda que é executada em cada elemento da lista e retorna verdadeiro se for maior que 4.
4. Imprima o resultado retornado pela função de filtro.
lambdas no mapa()
The map function is used to apply a particular operation to every element in a sequence. Like filter(), it also takes 2 parameters:
- A function that defines the operation to perform on the elements
- Uma ou mais sequências
Por exemplo, aqui está um programa que imprime os quadrados dos números em uma determinada lista:
sequences = [10,2,8,7,5,4,3,11,0, 1] filtered_result = map (lambda x: x*x, sequences) print(list(filtered_result))
Saída:
[100, 4, 64, 49, 25, 16, 9, 121, 0, 1]
Code Explicação:
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 em redução()
A função de redução, como map(), é usada para aplicar uma operação a cada elemento em uma sequência. No entanto, difere do mapa no seu funcionamento. Estas são as etapas seguidas pela função reduzir() para calcular uma saída:
Passo 1) Execute a operação definida nos 2 primeiros elementos da sequência.
Passo 2) Save this result.
Passo 3) Execute a operação com o resultado salvo e o próximo elemento da sequência.
Passo 4) Repita até que não restem mais elementos.
Também leva dois parâmetros:
- Uma função que define a operação a ser executada
- Uma sequência (qualquer iterador como listas, tuplas, etc.)
Por exemplo, aqui está um programa que retorna o produto de todos os elementos de uma lista:
from functools import reduce sequences = [1,2,3,4,5] product = reduce (lambda x, y: x*y, sequences) print(product)
Aqui está o resultado:
120
Code Explicação:
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 que (e por que não) usar funções lambda?
Como você verá na próxima seção, lambdas são tratadas da mesma forma que funções regulares no nível do intérprete. De certa forma, você poderia dizer que lambdas fornecem sintaxe compacta para escrever funções que retornam uma única expressão.
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 suporta um paradigma (ou estilo) de programação conhecido como programação 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.
Quando você não deve usar o Lambda?
Você nunca deve escrever funções lambda complicadas em um ambiente de produção. Será muito difícil para os codificadores que mantêm seu código descriptografá-lo. Se você estiver criando expressões complexas de uma linha, seria uma prática muito superior definir uma função adequada. Como prática recomendada, lembre-se de que código simples é sempre melhor que código complexo.
Lambdas vs. funções 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 | Funções regulares |
|---|---|
Sintaxe:
lambda x : x + x
|
Sintaxe:
def (x) : return x + x |
| As funções Lambda só podem ter uma expressão em seu corpo. | Funções regulares podem ter múltiplas expressões e instruções em seu corpo. |
| Lambdas do not have a name associated with them. That is why they are also known as anonymous functions. | Funções regulares devem ter nome e assinatura. |
| Lambdas não contêm uma instrução return porque o corpo é retornado automaticamente. | Functions which need to return a value should include a return statement. |
Explicação das diferenças
A principal diferença entre uma função lambda e uma função regular é que a função lambda avalia apenas uma única expressão e produz um objeto de função. Conseqüentemente, podemos nomear o resultado da função lambda e usá-lo em nosso programa como fizemos no exemplo anterior.
Uma função regular para o exemplo acima seria assim:
def adder (x, y): return x + y print (adder (1, 2))
Aqui, temos que definir um nome para a função que Retorna o resultado quando nós chamada 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 Pythonfunções integradas do.
No entanto, você ainda deve estar se perguntando como os lambdas são diferentes de uma função que retorna uma única expressão (como a acima). No nível do intérprete, não há muita diferença. Pode parecer surpreendente, mas qualquer função lambda definida em Python é tratada como uma função normal pelo 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 é reservado por Python, but any other function name will yield the same bytecode.
