Python Lambda
A lambda is a small function written in a single expression, without a name. You will mostly use lambdas as short “key” or “rule” functions passed to sorted(), max(), map() and filter().
- Write a lambda expression
- Sort data with a lambda key
- Transform and filter with map() and filter()
- Know when a normal def is better
Lambda syntax
lambda parameters: expression. The expression’s value is returned automatically; there is no return keyword.
square = lambda x: x * xadd = lambda a, b: a + b print(square(6), add(2, 3))36 5
The two lines above are equivalent to:
def square(x): return x * x print(square(6))36
Assigning a lambda to a name, as in the first example, works but PEP 8 recommends def for that. Lambdas are meant to be used inline, where a function is needed only once.
Sort with a lambda key
key tells sorted() what to compare. The lambda receives each item and returns the value to sort by.
employees = [("Asha", 52000), ("Ravi", 61000), ("Meena", 48000)] by_salary = sorted(employees, key=lambda e: e[1])print(by_salary) by_name_desc = sorted(employees, key=lambda e: e[0], reverse=True)print([name for name, _ in by_name_desc])[('Meena', 48000), ('Asha', 52000), ('Ravi', 61000)]
['Ravi', 'Meena', 'Asha']Sort dictionaries, or sort by several things at once by returning a tuple:
users = [{"name": "ravi", "age": 31}, {"name": "asha", "age": 28}, {"name": "meena", "age": 31}]print([u["name"] for u in sorted(users, key=lambda u: (-u["age"], u["name"]))])['meena', 'ravi', 'asha']
max() and min() with a key
words = ["python", "is", "readable"]print(max(words, key=lambda w: len(w))) prices = {"pen": 10, "bag": 650, "book": 120}print(min(prices, key=lambda k: prices[k]))readable pen
map(): transform every item
map(function, iterable) applies the function to each item and returns an iterator. Wrap it in list() to see the results.
celsius = [0, 25, 37.5, 100]fahrenheit = list(map(lambda c: c * 9 / 5 + 32, celsius))print(fahrenheit) print(list(map(str.upper, ["get", "post"]))) # any function works, not just lambdas[32.0, 77.0, 99.5, 212.0] ['GET', 'POST']
filter(): keep matching items
filter(function, iterable) keeps the items for which the function returns a truthy value.
scores = [45, 82, 67, 91, 38]print(list(filter(lambda s: s >= 50, scores)))[82, 67, 91]
A list comprehension is often clearer than map or filter with a lambda: [c * 9 / 5 + 32 for c in celsius] and [s for s in scores if s >= 50] do the same jobs. Use whichever reads better.
Lambdas with default values
apply_discount = lambda price, pct=10: round(price * (1 - pct / 100), 2)print(apply_discount(500), apply_discount(500, 25))450.0 375.0
Limits of lambda
A lambda can contain only one expression: no statements, no if blocks (a conditional expression is fine), no loops, no assignments.
grade = lambda m: "pass" if m >= 50 else "fail"print(grade(72), grade(31))pass fail
bad = lambda x: y = x + 1 File "main.py", line 1
bad = lambda x: y = x + 1
^^^^^^^^^^^
SyntaxError: cannot assign to lambdaIf the logic needs more than one line, write a normal def.
Check your understanding
Predict the output
pairs = [(1, "b"), (3, "a"), (2, "c")]print(sorted(pairs, key=lambda p: p[1]), list(map(lambda p: p[0] * 10, pairs)))[(3, 'a'), (1, 'b'), (2, 'c')] [10, 30, 20]
The first sorts by the letter in each pair. The second multiplies the number in each pair by 10, keeping the original order.
Quick quiz
1. What does (lambda x, y: x * y)(3, 4) return?
The lambda is called immediately with 3 and 4.
2. Which is NOT allowed in a lambda?
Lambdas hold a single expression only.
3. What does map() return in Python 3?
Convert it with list() to see all values at once.
Exercise: sort products
Sort the products by price, cheapest first, then print the names of products costing more than 100 using filter.
[("pen", 10), ("bag", 650), ("book", 120), ("tape", 35)][('pen', 10), ('tape', 35), ('book', 120), ('bag', 650)]
['bag', 'book']Hint 1
key=lambda p: p[1] sorts by price.
products = [("pen", 10), ("bag", 650), ("book", 120), ("tape", 35)] cheapest_first = sorted(products, key=lambda p: p[1])print(cheapest_first) expensive = filter(lambda p: p[1] > 100, products)print([name for name, price in expensive])[('pen', 10), ('tape', 35), ('book', 120), ('bag', 650)]
['bag', 'book']The sort key picks the price out of each tuple. filter keeps products over 100, and the comprehension pulls out just the names.
Program Practice
39 Python Function Programs
Every program has a step-by-step explanation, colour-coded code and its real output.
Python lambda FAQ
What is a lambda function in Python?
A lambda is an anonymous function written as a single expression: lambda x: x * 2. It is used for short functions passed to other functions.
Can a lambda have multiple lines?
No. A lambda holds exactly one expression. Use def for anything longer.
When should I use lambda instead of def?
Use a lambda for a short throwaway function passed as an argument, such as a key for sorted(). Use def when the function is reused, needs a name, or has more than one step.