A lambda in Python is a small anonymous function written on one line as lambda parameters: expression. It returns the value of that single expression, and it is mostly used for short throwaway functions such as a sort key.
add = lambda a, b: a + b
print(add(2, 3)) # 5
That is the whole idea. The rest of this article covers the exact syntax, the places lambdas are actually useful, and the limits that make def the better choice in other cases.
Lambda syntax in Python
The grammar in the Python language reference is lambda_expr: "lambda" [parameter_list] ":" expression. Three things follow from it:
- There is no
returnkeyword. The value of the expression after the colon is what the function returns. - The parameter list is optional and has the same syntax as in a
defstatement, so defaults,*argsand**kwargsall work. - The body is exactly one expression. It cannot be a block of statements.
The reference says a lambda "behaves like a function object defined with" def <lambda>(parameters): return expression. The Python tutorial adds that lambdas are "just syntactic sugar for a normal function definition." So the two forms below produce the same kind of object:
def add(a, b):
return a + b
add = lambda a, b: a + b
A lambda with no parameters is also valid: lambda: 42 returns 42 every time it is called. One difference you can see is the name. A function made by def add is named add, while a lambda has the placeholder name <lambda>, which shows up in tracebacks and makes debugging a little harder.
Examples of lambda functions
These are the cases where a lambda reads well. The first two come straight from the official documentation.
Sort a list with a lambda key
The most common use is the key argument of sorted() and list.sort(). The key function receives one item and returns the value to sort by. This example is from the Python sorting how-to:
student_tuples = [
('john', 'A', 15),
('jane', 'B', 12),
('dave', 'B', 10),
]
sorted(student_tuples, key=lambda student: student[2]) # sort by age
Example output:
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
The lambda returns index 2 of each tuple, the age, so the list is ordered by age. Add reverse=True to sort from oldest to youngest. The how-to also notes that the key function is called exactly once for each input record.
The tutorial shows the same idea with list.sort(), sorting pairs by their second element:
pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key=lambda pair: pair[1])
print(pairs)
Example output:
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
The strings 'four', 'one', 'three', 'two' are now in alphabetical order.
Return a function from a function
A lambda can use variables from the function that contains it. The tutorial's example builds an adder:
def make_incrementor(n):
return lambda x: x + n
f = make_incrementor(42)
print(f(0)) # 42
print(f(1)) # 43
Each call to make_incrementor creates its own n, so make_incrementor(10) would give you a separate function that adds 10.
Pass a lambda to map() and filter()
Built-in functions that take a function as an argument accept a lambda. map() applies the function to every item, and filter() keeps the items for which it returns a true value:
numbers = [1, 2, 3, 4, 5, 6]
print(list(map(lambda n: n * n, numbers)))
print(list(filter(lambda n: n % 2 == 0, numbers)))
Example output:
[1, 4, 9, 16, 25, 36]
[2, 4, 6]
You can check the arithmetic by hand: squares of 1 to 6, then the even numbers among them. For these two jobs a list comprehension is often easier to read, for example [n * n for n in numbers]. See Python list comprehension for that form.
Use a conditional expression inside a lambda
Because the body is an expression, you can use x if condition else y in it, but you cannot use an if statement:
label = lambda score: "pass" if score >= 50 else "fail"
print(label(72)) # pass
print(label(31)) # fail
What a lambda cannot do
The language reference states that functions created with lambda expressions cannot contain statements or annotations. In practice that rules out the following inside the body:
- Assignment with
=(a walrus expression:=is an expression, but it is rarely a good idea in a lambda). return,raise,try,with,forandwhilestatements.- Type annotations on the parameters or the return value.
- A docstring.
If you try to write a statement in the body, Python raises SyntaxError when it compiles the file. For example, lambda x: return x is a syntax error, because return is a statement. Drop the keyword and write lambda x: x. When the logic needs several steps, switch to a named function. See how to define a function with def and the return statement.
Why lambdas in a loop all return the same value
This is the most common surprise. The Python FAQ gives this example:
squares = []
for x in range(5):
squares.append(lambda: x**2)
print(squares[2]()) # 16, not 4
print(squares[4]()) # 16
You might expect 0, 1, 4, 9 and 16. Every lambda returns 16. The cause, per the FAQ, is that x is not local to the lambda. It lives in the outer scope and is looked up when the lambda is called, not when it is defined. After the loop ends, x is 4, so every function computes 4**2.
The fix is to bind the current value as a default argument, which is evaluated when the lambda is created:
squares = []
for x in range(5):
squares.append(lambda n=x: n**2)
print(squares[2]()) # 4
print(squares[4]()) # 16
The FAQ points out that this behaviour is not specific to lambdas. Regular functions defined in a loop do the same thing.
Lambda or def: which should you use?
Use a lambda when the function is short, used once, and passed straight into another call, such as a sort key. Use def when any of these apply:
- You assign the lambda to a name and call it in several places. A
defgives the function a real name, a docstring and annotations. - The expression no longer fits comfortably on one line.
- You want a useful name in an error traceback instead of
<lambda>.
For sort keys that just pick an item or attribute, the standard library has ready-made alternatives. The sorting how-to shows that operator.itemgetter(2) and operator.attrgetter('age') give the same results as the lambdas above, and describes them as simpler and faster:
from operator import itemgetter
sorted(student_tuples, key=itemgetter(2))
Common errors with lambda
SyntaxError: invalid syntaxafterlambda: you put a statement such asreturnor an assignment in the body. Use a single expression.TypeError: <lambda>() missing 1 required positional argument: you called the lambda with fewer arguments than its parameter list. The error message names the function<lambda>, exactly as a missing argument would for any function.- Wrong results from lambdas created in a loop: see the section above and bind the loop variable with a default argument.
- Forgetting to call it:
lambda: 5on its own is a function object, not 5. Call it with(lambda: 5)()or store it first.
Frequently asked questions
- What does lambda mean in Python?
- In Python, lambda is a keyword that creates a small anonymous function from a single expression. The expression lambda a, b: a + b gives you a function object that returns the sum of its two arguments, with no name and no def statement.
- Is a lambda faster than a def function?
- No. The Python language reference says a lambda behaves like a function defined with def and a body of one return statement, so it is the same kind of object. Choose between them for readability, not speed.
- Can a lambda contain more than one statement?
- No. A lambda body is a single expression, and the language reference states that lambda functions cannot contain statements or annotations. If you need assignments, loops or several steps, use def.
- Can a lambda have default arguments or take no arguments?
- Yes to both. The parameter list is optional, so lambda: 42 is valid, and it accepts the same parameter syntax as def, including defaults such as lambda n=3: n * 2.