Learning to program with Python - the practical tutorial

Lambda functions in Python: Passing short functions directly

All videos of the tutorial Learning to program with Python - the practical tutorial
Jan Brinkmann
By Jan Brinkmann Last updated on Shown in: Python 3.6

Imagine you need a calculation in exactly one place in your program. A separate function with a name and def quickly feels like overkill for that. This is exactly where so-called lambda functions come in, which in Python are also called anonymous functions. They replace short functions with a single expression that you write right where you need it.

Programming with Python - 7.7 Lambda functions

The video is only loaded from YouTube when you play it – data (including your IP address) is then transmitted to YouTube/Google. More in the privacy policy

In this tutorial, you will use an example from online retail to learn how to write a classic function for price calculation, pass it to another function, and then replace it with a lambda function. In the end, you will recognize when using one is worthwhile and when you are better off sticking with a normal function.

Key Takeaways

  • A lambda function is a short, nameless function that consists of exactly one expression.
  • The syntax is lambda parameter: expression. The expression is evaluated and its result is returned; a return is not necessary.
  • You can pass functions as arguments without calling them. To do this, you write the name of the function without parentheses.
  • Lambda functions produce the same result as a normal function, but are shorter and are suitable for simple calculations.

Step-by-Step Guide

Step 1: Understanding the Starting Point with a Price List

You start with a list of purchase prices. In the example, these are the values 4, 9, 16, 23, and 42. These numbers are deliberately chosen arbitrarily, because this is about the principle and not about real product data. Store the list in a variable called preise, and you have the foundation for everything that follows.

Lambda functions in Python: Passing short functions directly

Step 2: Writing a Classic Function for Price Calculation

Next, you define a function get_vk that calculates the selling price. The selling price is made up of the purchase price, a standard retail margin of 40 percent, and a flat shipping fee of 2 euros. A margin of 40 percent means that you multiply the purchase price by 1.4. Then you add the 2 euros for shipping.

def get_vk(ek):
    return ek * 1.4 + 2

The function thus takes a purchase price and directly returns the selling price. The actual core is just this one line with the calculation.

Lambda Functions in Python: Passing Short Functions Directly

Step 3: Building a Loop for the Price List

Now you need a place where the prices are processed. Imagine a category view in a shop. For this, you write a function that takes a list of purchase prices and additionally a calculation function. Inside this function, you iterate through the prices with a loop and call the passed function for each purchase price.

def preislisting(preise, berechnung):
    for ek in preise:
        print(berechnung(ek))

Make sure that the function get_vk is called inside the loop with the value ek. The name berechnung serves here only as a placeholder for the passed function.

Lambda Functions in Python: Passing Short Functions Directly

Step 4: Passing a Function as a Reference

Now comes the crucial point. You call preislisting and pass the list preise as well as the name of the function get_vk. It is important that you write get_vk without parentheses. With parentheses, you would execute the function immediately, and the result would be passed to preislisting. Without parentheses, you only pass a reference to the function.

preislisting(preise, get_vk)

Run the program. You will now see selling prices such as 4 euros, 9 euros, and so on, although some of the values are uneven. The formatting is secondary at this moment. What matters is that the function is called for each price.

Lambda functions in Python: Passing short functions directly

Step 5: Replacing the Calculation with a Lambda Function

The function get_vk contains only a single calculation. Lambda functions are suitable for exactly such cases. You can pass the calculation directly as an argument without naming a separate function.

The structure consists of three parts. First, you write the keyword lambda. Next comes the parameter name that the function receives when it is called. After the colon comes the expression that is to be calculated with this parameter.

preislisting(preise, lambda ek: ek * 1.4 + 2)

Here the parameter is called ek. It corresponds to the purchase price that is passed in on each loop iteration. The expression ek * 1.4 + 2 is exactly the calculation from the previous function. The lambda function therefore takes on the same task, but needs neither a name nor a return statement.

Lambda functions in Python: Passing short functions directly
Lambda functions in Python: Passing short functions directly

Step 6: Compare the result with the old version

To verify that both variants work the same way, you can first comment out the old function. To do this, put a # in front of the definition and the previous call. Then run the program again. You will notice that the output remains unchanged. If you then delete the commented-out lines completely, you have leaner code that does the same thing.

Lambda functions in Python: Passing short functions directly
Lambda functions in Python: Passing short functions directly

Step 7: Evaluate the Python way

The difference between the two variants lies mainly in the length of the code. The lambda variant consists of just one short statement, while the normal function requires several lines. The results are identical. Lambda functions are thus a typical Python solution for simple calculations that are used only once. As soon as a calculation becomes more complex or is needed in several places, a named function is worthwhile again, because it is more readable and easier to reuse.

Lambda Functions in Python: Passing Short Functions Directly

Summary – Lambda functions in Python: Passing short functions directly

You have seen how to write a classic function for calculating selling prices and pass it to a loop. You then replaced this function with a lambda function that accomplishes the same task in a single line. The key is to pass functions without parentheses and to write the calculation directly where it is needed. Lambda functions are especially useful when you need a short calculation only once.

FAQ

What is a lambda function in Python?A lambda function is a short, nameless function that consists of a single expression. It is defined with the keyword lambda.

Why are no parentheses used when passing it?With parentheses, the function would be executed immediately. Without parentheses, you only pass a reference, so that the function can be used later by the calling function.

Does a lambda function need a return?No. The result of the expression after the colon is returned automatically.

Can a lambda function contain multiple lines?No. A lambda function always consists of only a single expression. For multi-line logic, you need a normal function with def.

When should I use a normal function instead?If the calculation is more complex, is needed multiple times, or requires a meaningful name, a normal function with def is more readable and easier to maintain.

Jan Brinkmann
Trainer About Jan Brinkmann Web development with passion! Jan has been a developer for over 15 years. All courses by Jan Brinkmann