Python Lambdafunktioner med EXEMPEL

โšก Smart sammanfattning

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.
  • ๐Ÿค– AI-hjรคlp: AI assistants such as GitHub Copilot generate lambda expressions for map, filter, and sort keys from a short prompt.

Python Lambda-funktioner

Vad รคr Lambda-funktionen i Python?

A Lambdafunktion in Python programmering รคr en anonym funktion eller en funktion utan namn. Det รคr en liten och begrรคnsad funktion som inte har mer รคn en rad. Precis som en normal funktion kan en Lambda-funktion ha flera argument med ett uttryck.

In Python, anvรคnds lambda-uttryck (eller lambda-former) fรถr att konstruera anonyma funktioner. Fรถr att gรถra det anvรคnder du lambda nyckelord (precis som du anvรคnder def fรถr att definiera normala funktioner). Varje anonym funktion du definierar i Python kommer att ha 3 viktiga delar:

  • Lambda nyckelordet.
  • Parametrarna (eller bundna variabler), och
  • Funktionskroppen.

En lambdafunktion kan ha hur mรฅnga parametrar som helst, men funktionskroppen kan bara innehรฅlla ett uttryck. Dessutom skrivs en lambda i en enda kodrad och kan รคven anropas omedelbart. Du kommer att se allt detta i aktion i de kommande exemplen.

Syntax och exempel

Den formella syntaxen fรถr att skriva en lambdafunktion รคr enligt nedan:

lambda p1, p2: expression

Hรคr รคr p1 och p2 parametrarna som skickas till lambdafunktionen. Du kan lรคgga till sรฅ mรฅnga eller fรฅ parametrar som du behรถver.

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.

Exempelvis 1

Nu nรคr du kรคnner till lambdas lรฅt oss prova det med ett exempel. Sรฅ รถppna din IDLE och skriv in fรถljande:

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

Code Fรถrklaring

Hรคr definierar vi en variabel som kommer att hรฅlla resultatet som returneras av lambda-funktionen.

1. Nyckelordet lambda anvรคnds fรถr att definiera en anonym funktion.

2. x och y รคr parametrarna som vi skickar till lambdafunktionen.

3. Detta รคr huvuddelen av funktionen, som lรคgger till de 2 parametrarna vi skickade. Lรคgg mรคrke till att det รคr ett enda uttryck. Du kan inte skriva flera pรฅstรฅenden i kroppen av en lambdafunktion.

4. Vi anropar funktionen och skriver ut det returnerade vรคrdet.

Exempelvis 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 och skriv in fรถljande:

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

Spara nu din fil och tryck pรฅ F5 fรถr att kรถra programmet. Det hรคr รคr resultatet du bรถr fรฅ.

Produktion:

<function <lambda> at 0x00000185C3BF81E0>

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

Code Fรถrklaring:

1. Here, we define a strรคng 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 kallas by the print function but is simply tillbaka the function object and the memory location where it is stored. That is what gets printed at the console.

Exempelvis 3

Men om du skriver ett program som detta:

#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.

Produktion:

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 Fรถrklaring:

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.

Exempelvis 4

Let us look at a final example to understand how lambdas and regular functions are executed. So, open your IDLE och i en ny fil skriver du in fรถljande:

#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.

Produktion:

printer 1 REGULAR CALL

printer 2 REGULAR CALL

printer 1 LAMBDA CALL

printer 2 LAMBDA CALL

Code Fรถrklaring:

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.

I nรคsta avsnitt fรฅr du lรคra dig hur du anvรคnder lambdafunktioner med Karta(), minska()och filtrera() in Python.

Anvรคnder lambdas med Python inbyggda

Lambdafunktioner ger ett elegant och kraftfullt sรคtt att utfรถra operationer med hjรคlp av inbyggda metoder Python. Det รคr mรถjligt eftersom lambdas kan anropas omedelbart och skickas som ett argument till dessa funktioner.

IIFE in Python Lambda

IIFE stรฅr fรถr omedelbart anropade funktionsexekvering. 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 och skriv in fรถljande:

 (lambda x: x + x)(2)

Hรคr รคr utdata och kodfรถrklaring:

Denna fรถrmรฅga hos lambdas att anropas omedelbart gรถr att du kan anvรคnda dem i funktioner som map() och reduce(). Det รคr anvรคndbart eftersom du kanske inte vill anvรคnda dessa funktioner igen.

lambdas i filter()

Filterfunktionen anvรคnds fรถr att vรคlja vissa speciella element frรฅn en sekvens av element. Sekvensen kan vara vilken iterator som helst som listor, uppsรคttningar, tupler, etc.

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

  • En funktion som definierar filtreringsbegrรคnsningen
  • En sekvens (valfri iterator som listor, tupler, etc.)

Till exempel,

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

Hรคr รคr utgรฅngen:

[10, 8, 7, 5, 11]

Code Fรถrklaring:

1. I det fรถrsta pรฅstรฅendet definierar vi en lista som kallas sekvenser som innehรฅller nรฅgra siffror.

2. Hรคr deklarerar vi en variabel som heter filtered_result, som kommer att lagra de filtrerade vรคrdena som returneras av filter()-funktionen.

3. En lambda-funktion som kรถrs pรฅ varje element i listan och returnerar sant om det รคr stรถrre รคn 4.

4. Skriv ut resultatet som returneras av filterfunktionen.

lambdas i kartan()

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. En eller flera sekvenser

Till exempel, hรคr รคr ett program som skriver ut kvadraterna av siffror i en given lista:

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

Produktion:

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

Code Fรถrklaring:

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 i reduce()

Reduceringsfunktionen, som map(), anvรคnds fรถr att tillรคmpa en operation pรฅ varje element i en sekvens. Den skiljer sig dock frรฅn kartan i sin funktion. Det hรคr รคr stegen som fรถljs av reduce()-funktionen fรถr att berรคkna en utdata:

Steg 1) Utfรถr den definierade operationen pรฅ de tvรฅ fรถrsta elementen i sekvensen.

Steg 2) Save this result.

Steg 3) Utfรถr operationen med det sparade resultatet och nรคsta element i sekvensen.

Steg 4) Upprepa tills inga fler element finns kvar.

Det krรคvs ocksรฅ tvรฅ parametrar:

  1. En funktion som definierar operationen som ska utfรถras
  2. En sekvens (valfri iterator som listor, tupler, etc.)

Till exempel, hรคr รคr ett program som returnerar produkten av alla element i en lista:

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

Hรคr รคr utgรฅngen:

120

Code Fรถrklaring:

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.

Varfรถr (och varfรถr inte) anvรคnda lambdafunktioner?

Som du kommer att se i nรคsta avsnitt behandlas lambdas pรฅ samma sรคtt som vanliga funktioner pรฅ tolknivรฅ. Pรฅ ett sรคtt kan man sรคga att lambdas ger kompakt syntax fรถr att skriva funktioner som returnerar ett enda uttryck.

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 stรถder ett paradigm (eller stil) av programmering som kallas funktionell programmering.

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.

Nรคr ska du inte anvรคnda Lambda?

Du ska aldrig skriva komplicerade lambdafunktioner i en produktionsmiljรถ. Det kommer att vara mycket svรฅrt fรถr kodare som underhรฅller din kod att dekryptera den. Om du kommer pรฅ dig sjรคlv med att gรถra komplexa enkelriktade uttryck, skulle det vara en mycket รถverlรคgsen praxis att definiera en korrekt funktion. Som en bรคsta praxis mรฅste du komma ihรฅg att enkel kod alltid รคr bรคttre รคn komplex kod.

Lambdas kontra vanliga funktioner

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 Vanliga funktioner
Syntax:

lambda x : x + x
Syntax:

def (x) :
return x + x 
Lambdafunktioner kan bara ha ett uttryck i sin kropp. Reguljรคra funktioner kan ha flera uttryck och uttalanden i kroppen.
Lambdas do not have a name associated with them. That is why they are also known as anonymous functions. Vanliga funktioner mรฅste ha namn och signatur.
Lambdas innehรฅller inget returmeddelande eftersom kroppen automatiskt returneras. Functions which need to return a value should include a return statement.

Explanation of the differences

Den primรคra skillnaden mellan en lambda och en vanlig funktion รคr att lambdafunktionen endast utvรคrderar ett enda uttryck och ger ett funktionsobjekt. Fรถljaktligen kan vi namnge resultatet av lambdafunktionen och anvรคnda den i vรฅrt program som vi gjorde i fรถregรฅende exempel.

En vanlig funktion fรถr exemplet ovan skulle se ut sรฅ hรคr:

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

Hรคr mรฅste vi definiera en namn fรถr den funktion som รฅtergรฅr resultatet nรคr vi Ring 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 Pythons inbyggda funktioner.

Men du kanske fortfarande undrar hur lambda skiljer sig frรฅn en funktion som returnerar ett enda uttryck (som det ovan). Pรฅ tolknivรฅ รคr det inte sรฅ stor skillnad. Det kanske lรฅter รถverraskande, men vilken lambdafunktion som helst som du definierar i Python behandlas som en normal funktion av tolken.

At the bytecode level, the two definitions are handled in the same way by the Python interpreter. Now, you cannot name a function lambda eftersom det รคr reserverat av Python, but any other function name will yield the same bytecode.

Vanliga frรฅgor

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.

Sammanfatta detta inlรคgg med: