Execute Program

Python for Programmers: Lambda Expressions

Welcome to the Lambda Expressions lesson!

This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!

  • Some languages, most notably JavaScript, have function definitions that are also expressions. That lets us assign function definitions to variables. Here's some JavaScript code that defines a variable with const double and assigns a function to it:

  • >
    // This is JavaScript, not Python!
    const double = function (x) {
    return x * 2
    };

    double(3);
    Result:
  • We can't do that with Python's def because it's a statement, not an expression. The difference is that expressions have values, but statements don't. 1 + 1, f(x), and (name, email) are all expressions. if, for, and def are all statements. We can't say x = if ..., or x = def double(x):.

  • Trying to assign a def to a variable is a syntax error.

  • >
    double = def double(x): return x * 2
    double(3)
    Result:
    SyntaxError: invalid syntax (<string>, line 1)Pass Icon
  • However, expression syntax for function definitions is useful, so Python has a way to do it: the lambda keyword. Lambdas allow us to define small, inline functions and assign them to variables.

  • >
    always_blue = lambda: "blue"
    always_blue()
    Result:
    'blue'Pass Icon
  • Lambda functions can take arguments, just like regular def functions. The function below takes two arguments, x, and y.

  • >
    add = lambda x, y: x + y
    add(2, 3)
    Result:
    5Pass Icon
  • While parentheses around arguments are required in def, they're not allowed at all in lambda. Adding parentheses causes a syntax error.

  • >
    add = lambda (x, y): x + y
    add(2, 3)
    Result:
    SyntaxError: Lambda expression parameters cannot be parenthesized (<string>, line 1)Pass Icon
  • Also unlike def, lambdas don't need a return. That's because a lambda's body always contains exactly one expression: never two expressions, and never a statement. Because there's only one expression, Python knows that we must want to return it.

  • Because lambdas can only contain expressions, we can't use if, while, for, def, or assignments with =. All of those are statements. Trying to use any statement inside of a lambda function is a syntax error.

  • >
    x = [0, 0]
    assign_x_0 = lambda: x[0] = 1
    assign_x_0()
    x
    Result:
    SyntaxError: cannot assign to lambda (<string>, line 2)Pass Icon
  • Lambdas are "anonymous", meaning that they have no name. Contrast that with regular def functions, whose names are stored in the __name__ property.

  • >
    def double(x):
    return x * 2

    double.__name__
    Result:
  • >
    double = lambda x: x * 2
    double.__name__
    Result:
  • In the next example, we define two regular functions with def. We pass one function as an argument to the other function.

  • >
    def call_function(func, value):
    return func(value)

    def double(x):
    return x * 2

    call_function(double, 3)
    Result:
    6Pass Icon
  • We can rewrite that as a pair of lambda functions.

  • >
    call_function = lambda func, value: func(value)
    double = lambda x: x * 2

    call_function(double, 3)
    Result:
    6Pass Icon
  • We can even inline both function definitions, giving us a single line of code. In the next example, the two lambda functions are exactly the same as above.

  • >
    (lambda func, value: func(value))(lambda x: x * 2, 3)
    Result:
    6Pass Icon
  • You probably won't ever write that line of code, since it's the same as writing 6. But it does show how compact lambdas can be.

  • Here's a more common, real-world example of how lambdas are used. Lists have a .sort method that we saw briefly in another lesson. It sorts numbers from smallest to largest, and it sorts strings alphanumerically (first from "0" to "9", then from "a" to "z".)

  • >
    numbers = [8, 4, 5]
    numbers.sort()
    numbers
    Result:
    [4, 5, 8]Pass Icon
  • >
    strings = ["cat", "apple", "boat"]
    strings.sort()
    strings
    Result:
    ['apple', 'boat', 'cat']Pass Icon
  • Sometimes we want more control over how a list is sorted. For example, we might want to sort strings by their lengths, rather than by their alphanumeric values.

  • The .sort method takes an optional key argument for exactly this purpose. It calls the key function on each list element, then sorts the list elements according to those sort keys. This is a perfect use case for a lambda!

  • >
    strings = ["cat", "apple", "boat"]
    strings.sort(key=lambda string: len(string))
    strings
    Result:
    ['cat', 'boat', 'apple']Pass Icon
  • The key function can be any function, whether it was defined with def or lambda. However, key functions are often short, making lambda a good choice.

  • Finally, you might wonder why these are called "lambda" functions.

  • In the 1930s, Alonzo Church used the Greek letter λ (lambda) in what we now call "the lambda calculus", a formal system critical to the early history of computing. For example, the "identity function", a function that returns its argument, is written as λx. x.

  • The Python lambda syntax is directly descended from Alonzo Church's work, even though a century has passed: lambda x: x. The xs are the same, the λ becomes the word lambda written out, and the . becomes a :. And note that λx. x doesn't have a name, just like lambda x: x doesn't have a name.