Q1Which of the following is a valid lambda expression?
Lambda Expressions — Writing Anonymous Functions in One Line
Write one-line anonymous functions with Python lambdas and pair them with higher-order functions, all in your browser.
In the previous article on higher-order functions, you saw how to pass functions as arguments and return values. Defining a fresh function with def every time you need to hand off a callback means a one-line operation suddenly takes 3 or 4 lines.
That's where lambda expressions (lambda) come in — they let you write an anonymous function on a single line. Perfect for the small bits of logic that don't quite deserve a full def.
What Is a Lambda — Compared with def
The syntax is lambda args: expression. The result of expression becomes the return value directly, and you don't write return (in fact, doing so triggers a SyntaxError).
Unlike a normal function, a lambda has no name, so it can't be called unless you assign it to a variable. The variable name you assign it to effectively becomes the function's name.
# Written with def
def add_tax(price):
return int(price * 1.1)
print(add_tax(980)) # 1078
# Same logic as a lambda (no return needed)
add_tax = lambda price: int(price * 1.1)
print(add_tax(980)) # 1078
Only Expressions Allowed — No Statements
A lambda body can only contain an expression (something that evaluates to a value). if statements, for loops, and assignments (=) won't fit. The moment you want something more elaborate, switch back to def — that's the right call.
More Arguments, Conditional Expressions, and Defaults
Lambdas can take multiple arguments too. Just list them with commas, like lambda x, y: x * y.
You can also use default arguments the same way you do with def. To switch values based on a condition, drop a conditional expression value1 if condition else value2 into the body.
# Multiple arguments
rect_area = lambda width, height: width * height
print(rect_area(4, 5)) # 20
# Default argument (omit rate to use 0.1)
add_tax = lambda price, rate=0.1: int(price * (1 + rate))
print(add_tax(1000)) # 1100
print(add_tax(1000, 0.08)) # 1080
# Conditional expression
judge_age = lambda age: "adult" if age >= 20 else "minor"
print(judge_age(25)) # adult
print(judge_age(17)) # minor
# Return multiple values as a tuple
stats = lambda x, y: (x + y, x * y)
print(stats(3, 4)) # (7, 12)
lambda handles multiple arguments, default arguments, and branching with a conditional expression with the same feel as def.Pairing with Higher-Order Functions — Where Lambdas Shine
Lambdas really earn their keep when you want to hand a throwaway function to a higher-order function. For instance, sorted()'s key argument is a higher-order function that takes "a function that returns the sort key from each element."
For a sort order you don't need to name and reuse, writing key=lambda x: x["price"] inline at the call site is the most natural form.
products = [
{"name": "Notebook", "price": 480},
{"name": "Pen", "price": 120},
{"name": "Eraser", "price": 80},
]
# Sort by price ascending (pass an inline lambda as key)
cheap_first = sorted(products, key=lambda item: item["price"])
for item in cheap_first:
print(item["name"], item["price"])
# Eraser 80
# Pen 120
# Notebook 480
# The same higher-order function process_list can switch behavior via lambda
def process_list(numbers, func):
for n in numbers:
print(func(n))
process_list([1, 2, 3, 4], lambda x: x ** 2)
# 1
# 4
# 9
# 16
When to Use a Lambda — and When to Avoid One
Lambdas are convenient, but using them everywhere actually hurts readability. The table below sums it up: reach for lambdas for throwaway, one-line operations, and stick with def for anything complex or reused.
| Situation | Recommendation | Reason |
|---|---|---|
| Pass to sorted's key, filter, map | lambda | One line conveys intent; no need for a name |
| One-line expressions like tax-included price | lambda | A short named function with no import needed |
| Logic that needs if / for / try | def | lambda is expressions only; statements raise SyntaxError |
| Logic reused from multiple places | def | A name conveys intent and supports tests and docs |
| Bodies running 3+ lines | def | Cramming into a lambda only hurts readability |
Don't Cram Everything into a Lambda
Stack three nested conditional expressions or chain a few function calls together and you end up with code that's on one line but unreadable. The moment you think "I'd love to leave a comment explaining what this lambda does," reach for def instead.
Knowledge Check
Answer each question one by one.
Q2What does this code print?f = lambda x, y=3: x ** y
print(f(2))
Q3Which of the following is the most appropriate use of a lambda expression?