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 doubleand 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
defbecause 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, anddefare all statements. We can't sayx = if ..., orx = def double(x):.Trying to assign a
defto a variable is a syntax error.>
double = def double(x): return x * 2double(3)Result:
SyntaxError: invalid syntax (<string>, line 1)
However, expression syntax for function definitions is useful, so Python has a way to do it: the
lambdakeyword. Lambdas allow us to define small, inline functions and assign them to variables.>
always_blue = lambda: "blue"always_blue()Result:
'blue'
Lambda functions can take arguments, just like regular
deffunctions. The function below takes two arguments,x, andy.>
add = lambda x, y: x + yadd(2, 3)Result:
5
While parentheses around arguments are required in
def, they're not allowed at all inlambda. Adding parentheses causes a syntax error.>
add = lambda (x, y): x + yadd(2, 3)Result:
SyntaxError: Lambda expression parameters cannot be parenthesized (<string>, line 1)
Also unlike
def,lambdas don't need areturn. 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] = 1assign_x_0()xResult:
SyntaxError: cannot assign to lambda (<string>, line 2)
Lambdas are "anonymous", meaning that they have no name. Contrast that with regular
deffunctions, whose names are stored in the__name__property.>
def double(x):return x * 2double.__name__Result:
>
double = lambda x: x * 2double.__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 * 2call_function(double, 3)Result:
6
We can rewrite that as a pair of lambda functions.
>
call_function = lambda func, value: func(value)double = lambda x: x * 2call_function(double, 3)Result:
6
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:
6
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.sortmethod 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()numbersResult:
[4, 5, 8]
>
strings = ["cat", "apple", "boat"]strings.sort()stringsResult:
['apple', 'boat', 'cat']
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
.sortmethod takes an optionalkeyargument for exactly this purpose. It calls thekeyfunction on each list element, then sorts the list elements according to those sort keys. This is a perfect use case for alambda!>
strings = ["cat", "apple", "boat"]strings.sort(key=lambda string: len(string))stringsResult:
['cat', 'boat', 'apple']
The key function can be any function, whether it was defined with
deforlambda. However, key functions are often short, makinglambdaa 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. Thexs are the same, theλbecomes the wordlambdawritten out, and the.becomes a:. And note thatλx. xdoesn't have a name, just likelambda x: xdoesn't have a name.