Python Lambda-functies met VOORBEELDEN
โก Slimme samenvatting
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().

Waar zit de Lambda-functie in? Python?
A Lambda-functie in Python programmeren is een anonieme functie of een functie zonder naam. Het is een kleine en beperkte functie met niet meer dan รฉรฉn regel. Net als een normale functie kan een Lambda-functie meerdere argumenten hebben met รฉรฉn uitdrukking.
In Pythonworden lambda-expressies (of lambda-vormen) gebruikt om anonieme functies te construeren. Hiervoor maak je gebruik van de lambda trefwoord (net zoals u gebruikt def om normale functies te definiรซren). Elke anonieme functie die u definieert Python zal uit 3 essentiรซle onderdelen bestaan:
- Het lambda-trefwoord.
- De parameters (of gebonden variabelen), en
- Het functielichaam.
Een lambda-functie kan een willekeurig aantal parameters hebben, maar de hoofdtekst van de functie kan alleen maar bevatten een uitdrukking. Bovendien wordt een lambda in รฉรฉn regel code geschreven en kan deze ook direct worden aangeroepen. U zult dit allemaal in actie zien in de komende voorbeelden.
Syntaxis en voorbeelden
De formele syntaxis voor het schrijven van een lambdafunctie is zoals hieronder weergegeven:
lambda p1, p2: expression
Hier zijn p1 en p2 de parameters die worden doorgegeven aan de lambdafunctie. U kunt zoveel of weinig parameters toevoegen als u nodig heeft.
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.
Voorbeeld 1
Nu je weet wat lambda's zijn, laten we het proberen met een voorbeeld. Open dus uw IDLE en typ het volgende in:
adder = lambda x, y: x + y print (adder (1, 2))
Code Uitleg
Hier definiรซren we een variabele die het resultaat bevat dat wordt geretourneerd door de lambda-functie.
1. Het lambda-trefwoord dat wordt gebruikt om een โโanonieme functie te definiรซren.
2. x en y zijn de parameters die we doorgeven aan de lambda-functie.
3. Dit is de hoofdtekst van de functie, die de twee parameters toevoegt die we hebben doorgegeven. Merk op dat het een enkele uitdrukking is. U kunt niet meerdere instructies in de hoofdtekst van een lambda-functie schrijven.
4. We roepen de functie aan en drukken de geretourneerde waarde af.
Voorbeeld 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 en typ het volgende in:
#What a lambda returns string='some kind of a useless lambda' print(lambda string : print(string))
Sla nu uw bestand op en druk op F5 om het programma uit te voeren. Dit is de uitvoer die u zou moeten krijgen.
Output:
<function <lambda> at 0x00000185C3BF81E0>
What is happening here? Let us look at the code to understand further.
Code Uitleg:
1. Here, we define a snaar 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 genaamd by the print function but is simply terugkerende the function object and the memory location where it is stored. That is what gets printed at the console.
Voorbeeld 3
Als u echter een programma als dit schrijft:
#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.
Output:
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 Uitleg:
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.
Voorbeeld 4
Let us look at a final example to understand how lambdas and regular functions are executed. So, open your IDLE en typ in een nieuw bestand het volgende:
#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.
Output:
printer 1 REGULAR CALL printer 2 REGULAR CALL printer 1 LAMBDA CALL printer 2 LAMBDA CALL
Code Uitleg:
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.
In het volgende gedeelte leert u hoe u lambda-functies gebruikt kaart(), verminderen()en filter() in Python.
Lambda's gebruiken bij Python ingebouwde ins
Lambda-functies bieden een elegante en krachtige manier om bewerkingen uit te voeren met behulp van ingebouwde methoden in Python. Dit is mogelijk omdat lambdas onmiddellijk kunnen worden aangeroepen en als argument aan deze functies kunnen worden doorgegeven.
IIFE in Python Lambda
IIFE staat voor onmiddellijk een beroep gedaan op de uitvoering van de functie. 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 en typ het volgende in:
(lambda x: x + x)(2)
Hier is de uitvoer en code-uitleg:
Dankzij de mogelijkheid om lambda's onmiddellijk aan te roepen, kunt u ze gebruiken in functies zoals map() en reduce(). Het is handig omdat u deze functies mogelijk niet meer wilt gebruiken.
lambda's in filter()
De filterfunctie wordt gebruikt om bepaalde elementen uit een reeks elementen te selecteren. De reeks kan elke iterator zijn, zoals lijsten, sets, tupels, enz.
The elements which will be selected are based on some pre-defined constraint. It takes 2 parameters:
- Een functie die de filterbeperking definieert
- Een reeks (elke iterator zoals lijsten, tupels, enz.)
Bijvoorbeeld
sequences = [10,2,8,7,5,4,3,11,0, 1] filtered_result = filter (lambda x: x > 4, sequences) print(list(filtered_result))
Dit is de uitvoer:
[10, 8, 7, 5, 11]
Code Uitleg:
1. In de eerste zin definiรซren we een lijst met de naam reeksen die een aantal getallen bevat.
2. Hier declareren we een variabele genaamd filtered_result, die de gefilterde waarden opslaat die worden geretourneerd door de functie filter().
3. Een lambda-functie die op elk element van de lijst wordt uitgevoerd en waar retourneert als deze groter is dan 4.
4. Druk het resultaat af dat door de filterfunctie wordt geretourneerd.
lambda's in kaart()
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
- Eรฉn of meer reeksen
Hier is bijvoorbeeld een programma dat de kwadraten van getallen in een gegeven lijst afdrukt:
sequences = [10,2,8,7,5,4,3,11,0, 1] filtered_result = map (lambda x: x*x, sequences) print(list(filtered_result))
Output:
[100, 4, 64, 49, 25, 16, 9, 121, 0, 1]
Code Uitleg:
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.
lambda's in reduce()
De reduce-functie, zoals map(), wordt gebruikt om een โโbewerking toe te passen op elk element in een sequentie. Het verschilt echter van de map in zijn werking. Dit zijn de stappen die de reduce()-functie volgt om een โโuitvoer te berekenen:
Stap 1) Voer de gedefinieerde bewerking uit op de eerste 2 elementen van de reeks.
Stap 2) Save this result.
Stap 3) Voer de bewerking uit met het opgeslagen resultaat en het volgende element in de reeks.
Stap 4) Herhaal dit totdat er geen elementen meer over zijn.
Er zijn ook twee parameters nodig:
- Een functie die de uit te voeren bewerking definieert
- Een reeks (elke iterator zoals lijsten, tupels, enz.)
Hier is bijvoorbeeld een programma dat het product van alle elementen in een lijst retourneert:
from functools import reduce sequences = [1,2,3,4,5] product = reduce (lambda x, y: x*y, sequences) print(product)
Dit is de uitvoer:
120
Code Uitleg:
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.
Waarom (en waarom niet) lambda-functies gebruiken?
Zoals u in de volgende sectie zult zien, worden lambda's op dezelfde manier behandeld als reguliere functies op tolkniveau. In zekere zin zou je kunnen zeggen dat lambda's een compacte syntaxis bieden voor het schrijven van functies die รฉรฉn enkele expressie retourneren.
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 ondersteunt een paradigma (of stijl) van programmeren dat bekend staat als functioneel programmeren.
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.
Wanneer mag u Lambda niet gebruiken?
Je moet nooit ingewikkelde lambdafuncties schrijven in een productieomgeving. Het zal erg moeilijk zijn voor programmeurs die je code onderhouden om deze te decoderen. Als je merkt dat je complexe one-liner expressies maakt, zou het een veel betere gewoonte zijn om een โโgoede functie te definiรซren. Als best practice moet je onthouden dat simpele code altijd beter is dan complexe code.
Lambda's versus reguliere functies
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.
| Lambda's | Reguliere functies |
|---|---|
Syntax:
lambda x : x + x
|
Syntax:
def (x) : return x + x |
| Lambda-functies kunnen slechts รฉรฉn uitdrukking in hun lichaam hebben. | Reguliere functies kunnen meerdere expressies en instructies in hun lichaam hebben. |
| Lambdas do not have a name associated with them. That is why they are also known as anonymous functions. | Reguliere functies moeten een naam en handtekening hebben. |
| Lambda's bevatten geen retourverklaring omdat de body automatisch wordt geretourneerd. | Functions which need to return a value should include a return statement. |
Uitleg van de verschillen
Het belangrijkste verschil tussen een lambda- en een reguliere functie is dat de lambda-functie slechts รฉรฉn enkele expressie evalueert en een functieobject oplevert. Daarom kunnen we het resultaat van de lambda-functie een naam geven en in ons programma gebruiken, zoals we in het vorige voorbeeld deden.
Een reguliere functie voor het bovenstaande voorbeeld zou er als volgt uitzien:
def adder (x, y): return x + y print (adder (1, 2))
Hier moeten we a definiรซren naam voor de functie die Retourneren het resultaat toen wij Bellen 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 Pythoningebouwde functies.
U vraagt โโzich echter misschien nog steeds af hoe lambda's verschillen van een functie die een enkele expressie retourneert (zoals die hierboven). Op tolkniveau is er niet veel verschil. Het klinkt misschien verrassend, maar elke lambda-functie die je definieert Python wordt door de tolk als een normale functie behandeld.
At the bytecode level, the two definitions are handled in the same way by the Python interpreter. Now, you cannot name a function lambda omdat het gereserveerd is door Python, but any other function name will yield the same bytecode.
