Python Lambda
A lambda is a small, anonymous function written in a single expression. It's handy when you need a short function for a moment — typically as an argument to another function — and giving it a full def would be overkill.
Syntax
lambda parameters: expressionThe expression's value is returned automatically; there's no return keyword and no body block.
double = lambda x: x * 2
add = lambda a, b: a + b
greet = lambda: "hello"
print(double(21))
print(add(3, 4))
print(greet())42
7
hello
These two definitions are equivalent:
def version |
lambda version |
|---|---|
def square(n): return n * n |
square = lambda n: n * n |
Note: Assigning a lambda to a name, as above, is fine for demonstrating, but style guides prefer
defin that case — adeffunction has a proper name in error messages. Lambdas shine when used inline.
Lambdas as sort keys
The most common real-world use: telling sorted(), min(), max() or list.sort() what to compare:
students = [
{"name": "Vy", "score": 88},
{"name": "Bao", "score": 95},
{"name": "Quan", "score": 72},
]
ranked = sorted(students, key=lambda s: s["score"], reverse=True)
for s in ranked:
print(s["name"], s["score"])
best = max(students, key=lambda s: s["score"])
print("Top:", best["name"])
words = ["banana", "Apple", "cherry"]
print(sorted(words, key=lambda w: w.lower()))
print(sorted(words, key=lambda w: w[-1])) # by last letterBao 95
Vy 88
Quan 72
Top: Bao
['Apple', 'banana', 'cherry']
['banana', 'Apple', 'cherry']
Sorting by several criteria? Return a tuple. Tuples compare item by item:
people = [("Lan", 30), ("An", 25), ("Binh", 30), ("Chi", 25)]
print(sorted(people, key=lambda p: (p[1], p[0]))) # by age, then name[('An', 25), ('Chi', 25), ('Binh', 30), ('Lan', 30)]
map() and filter()
map(func, items) applies a function to every item; filter(func, items) keeps only the items for which the function returns a truthy value. Both return lazy iterators, so wrap them in list() to see the results:
prices = [10, 25, 40]
with_tax = list(map(lambda p: round(p * 1.1, 2), prices))
print(with_tax)
nums = range(1, 11)
evens = list(filter(lambda n: n % 2 == 0, nums))
print(evens)[11.0, 27.5, 44.0]
[2, 4, 6, 8, 10]
Tip: List comprehensions often read better than
map/filterwith a lambda:[p * 1.1 for p in prices]and[n for n in nums if n % 2 == 0]. Both styles are common; choose the clearer one.
Functions that create functions
A lambda can capture variables from the place where it's created. That lets you build customised functions on the fly:
def multiplier(factor):
return lambda x: x * factor
triple = multiplier(3)
half = multiplier(0.5)
print(triple(7))
print(half(9))21
4.5
The lambda "remembers" factor even after multiplier has returned. This is called a closure.
A lookup table of operations
Lambdas fit nicely into a dictionary that maps names to behaviour:
ops = {
"+": lambda a, b: a + b,
"-": lambda a, b: a - b,
"*": lambda a, b: a * b,
"/": lambda a, b: a / b,
}
for symbol in ["+", "-", "*", "/"]:
print(f"12 {symbol} 4 = {ops[symbol](12, 4)}")12 + 4 = 16
12 - 4 = 8
12 * 4 = 48
12 / 4 = 3.0
Limits of lambdas
| A lambda can | A lambda cannot |
|---|---|
| take any number of parameters, including defaults | contain statements (if blocks, loops, return, assignments) |
use a conditional expression a if c else b |
span multiple lines of logic |
| capture outer variables | have a docstring |
If your lambda gets hard to read, turn it into a regular def.
Test yourself
What does (lambda x, y: x * y)(3, 4) evaluate to?
- 7
- 12
- 34
- A lambda object
Which of these can a lambda body contain?
- A for loop
- An assignment statement
- A single expression
- Several return statements
What does sorted(["bb", "a", "ccc"], key=lambda s: -len(s)) return?
- ['a', 'bb', 'ccc']
- ['ccc', 'bb', 'a']
- ['bb', 'a', 'ccc']
- ['a', 'ccc', 'bb']