Skip to content

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.

  • The syntax of a lambda expression and how it differs from def.
  • The common use cases: sorted keys, map, filter, and reduce.
  • 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 def instead.
  • Python 3.9 or newer installed (run python --version to check).
  • Comfort with functions, lists, and for loops.
  • A way to run a script: save code as .py and run python filename.py.

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.97

Verify: The script prints 449.97. The lambda is created and called in one line.

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.

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.

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'].

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.97

Verify: 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.

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)) # large

Verify: The script prints large. Anything needing multiple statements belongs in a 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>" traceback
tax_via_lambda = lambda amt, rate: round(amt * rate, 2)
# Named def — the same logic done right
def 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.0
print(tax_via_def(149.99, 0.08)) # 12.0

Verify: 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.

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 tax
by_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.91
  • Assigning a lambda to a name. double = lambda x: x * 2 is legal but pointless. Use def double(x): return x * 2 so 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 if block, or a loop, switch to def. Lambdas cannot contain statements.
  • Ignoring existing built-ins. sum(x for x in nums) beats reduce(lambda a, b: a + b, nums), and a comprehension often beats map with 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 append or updates a dict is doing statement-style work through a side effect. Make it a def instead.
  • 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.