Python Lambda Functions: Anonymous One-Liners
A lambda is a function with no name, written as a single expression. Used well, it is a crisp way to hand a small operation to sorted, map, or filter. Used badly, it becomes a debugging headache that hides what a line does. This tutorial walks through OrdersPortal order data to show where a lambda reads clearly and where a plain def is the better choice.
What you’ll learn
Section titled “What you’ll learn”- The syntax of a
lambdaexpression and how it differs fromdef. - The common use cases:
sortedkeys,map,filter, andreduce. - The hard limits of lambdas: a single expression, no statements, no docstring.
- Why assigning a lambda to a name is an anti-pattern, and when to reach for
definstead.
Prerequisites
Section titled “Prerequisites”- Python 3.9 or newer installed (run
python --versionto check). - Comfort with functions, lists, and
forloops. - A way to run a script: save code as
.pyand runpython filename.py.
1. Write a lambda expression
Section titled “1. Write a lambda expression”A lambda is an anonymous function written as a single expression: lambda parameters: expression. It returns the value of that expression. There is no return keyword and no statements.
total = (lambda amount, qty: round(amount * qty, 2))(149.99, 3)print(total) # 449.97Verify: The script prints 449.97. The lambda is created and called in one line.
2. Sort with a key lambda
Section titled “2. Sort with a key lambda”The most common real use of a lambda is the key argument to sorted. The lambda extracts the value to sort by, leaving each element unchanged.
orders = [ {"id": "ORD-001", "amount": 149.99, "status": "shipped"}, {"id": "ORD-002", "amount": 49.99, "status": "pending"}, {"id": "ORD-003", "amount": 299.00, "status": "shipped"},]
cheapest = sorted(orders, key=lambda o: o["amount"])print([o["id"] for o in cheapest]) # ['ORD-002', 'ORD-001', 'ORD-003']Verify: The script prints ['ORD-002', 'ORD-001', 'ORD-003']. The original list is unchanged.
3. Transform with map
Section titled “3. Transform with map”map(function, iterable) applies the function to each item and returns an iterator. A short lambda is a natural fit for a one-off transformation.
orders = [149.99, 49.99, 19.99]with_tax = list(map(lambda amt: round(amt * 1.08, 2), orders))print(with_tax) # [161.99, 53.99, 21.59]Verify: The script prints the three amounts with 8% tax. Pass the result to list because map is lazy.
4. Filter with filter
Section titled “4. Filter with filter”filter(function, iterable) keeps the items for which the function returns a truthy value. A lambda predicate works well for a quick, one-off filter.
orders = [ {"id": "ORD-001", "amount": 149.99, "status": "shipped"}, {"id": "ORD-002", "amount": 49.99, "status": "pending"},]shipped = list(filter(lambda o: o["status"] == "shipped", orders))print([o["id"] for o in shipped]) # ['ORD-001']Verify: The script prints ['ORD-001'].
5. Reduce with functools.reduce
Section titled “5. Reduce with functools.reduce”reduce folds an iterable down to a single value by applying a function cumulatively. It lives in functools, and a lambda works for simple folds like a product or a running total.
from functools import reduce
orders = [149.99, 49.99, 19.99]grand_total = reduce(lambda a, b: round(a + b, 2), orders)print(grand_total) # 219.97Verify: The script prints 219.97. For a plain sum, sum(orders) is clearer and faster, so reach for reduce only when the operation does not have a built-in.
6. Know the limits
Section titled “6. Know the limits”A lambda body is a single expression. It cannot contain statements such as if/else blocks, for, while, assignments, or return, and it cannot carry a docstring. A conditional expression (ternary) is allowed because it is an expression.
classify = lambda amt: "large" if amt >= 100 else "small"print(classify(149.99)) # largeVerify: The script prints large. Anything needing multiple statements belongs in a def.
7. Know when to prefer def
Section titled “7. Know when to prefer def”A lambda is the right tool when the function is short, used once, and lives inline as an argument — a key for sorted is the canonical case. Reach for a def the moment the function needs a name you will reuse, a docstring, more than one expression, or a readable traceback. A named function shows up as apply_discount in a stack trace; a named lambda shows up as <lambda>, which tells you nothing when a test fails.
# Named lambda — anti-pattern: no docstring, opaque "<lambda>" tracebacktax_via_lambda = lambda amt, rate: round(amt * rate, 2)
# Named def — the same logic done rightdef tax_via_def(amt: float, rate: float) -> float: """Return the tax for an amount at the given rate.""" return round(amt * rate, 2)
print(tax_via_lambda(149.99, 0.08)) # 12.0print(tax_via_def(149.99, 0.08)) # 12.0Verify: Both lines print 12.0. The two are equivalent in result, but only the def carries a name, a docstring, and a usable traceback.
The linter rule E731 flags the assignment on the left as a code smell, and the fix is always to convert it to a def. Lambdas are best left anonymous: define them where you use them and pass them straight into the function that consumes them.
Complete working example
Section titled “Complete working example”Save this as orders_lambda.py and run python orders_lambda.py.
"""Process OrdersPortal orders with small lambdas."""from functools import reduce
orders = [ {"id": "ORD-001", "amount": 149.99, "status": "shipped"}, {"id": "ORD-002", "amount": 49.99, "status": "pending"}, {"id": "ORD-003", "amount": 299.00, "status": "shipped"}, {"id": "ORD-004", "amount": 19.99, "status": "cancelled"},]
# Sort by amount, then take only the shipped ones, then sum their totals with taxby_amount = sorted(orders, key=lambda o: o["amount"])shipped = list(filter(lambda o: o["status"] == "shipped", by_amount))taxed = list(map(lambda o: round(o["amount"] * 1.08, 2), shipped))grand_total = reduce(lambda a, b: round(a + b, 2), taxed)
print("shipped (cheapest first):", [o["id"] for o in shipped])print(f"grand total with tax: {grand_total:.2f}")Expected output:
shipped (cheapest first): ['ORD-001', 'ORD-003']grand total with tax: 484.91Common mistakes
Section titled “Common mistakes”- Assigning a lambda to a name.
double = lambda x: x * 2is legal but pointless. Usedef double(x): return x * 2so the function has a real name, a docstring, and a readable traceback. The lint rule E731 flags exactly this. - Using a lambda for anything multi-line. Once the logic needs statements, an
ifblock, or a loop, switch todef. Lambdas cannot contain statements. - Ignoring existing built-ins.
sum(x for x in nums)beatsreduce(lambda a, b: a + b, nums), and a comprehension often beatsmapwith a lambda. Use the clearest tool. - Complex sort keys in a lambda.
key=lambda o: (o["status"], o["amount"])is fine, but once the key needs computation or comments, move it to a named function. - Mutating inside a lambda. A lambda that calls
appendor updates a dict is doing statement-style work through a side effect. Make it adefinstead.
Next steps
Section titled “Next steps”- Functions basics —
def, parameters, defaults, andreturn, the foundations lambdas build on. - Comprehensions intro — the readable alternative to many
mapandfiltercalls. - Iterators and generators — what
mapandfilteractually return.
Related pages
Section titled “Related pages”- Python basics index — overview of every basics page in one place.
- Lists — the collections you sort and filter with lambdas.
- Dictionaries — sorting by keys and values, a top lambda use case.
Official references
Section titled “Official references”- docs.python.org: Lambdas — the grammar of lambda expressions.
- docs.python.org: Functional programming how-to —
map,filter, andreducein depth. - docs.python.org: Sorting how-to — using the
keyargument withsortedandlist.sort. - docs.python.org: The
functoolsmodule —reduceand other higher-order tools.