Lambda

Compact anonymous functions for expressions that don't need a name

Why

Lambda shows up everywhere Python uses functions as values — sorting, filtering, mapping, and callbacks. Knowing the syntax, knowing where it helps, and knowing when a def is cleaner signals idiomatic Python fluency.

Lambda makes functions first-class — you can pass them, return them, and compose them inline without naming them. Understanding this unlocks map, filter, sorted, and the full functional toolkit.

Intuition

A lambda is a function with no name. lambda x: x * 2 is exactly the same as writing def f(x): return x * 2 — except you can't write multiple statements or use return. The expression after the colon is the return value.

Think of it as a throwaway function — useful when you need a function once, inline, and naming it would just add noise.

Explanation
1. Syntax & Basics

A lambda is an anonymous function defined in a single expression. Arguments go before the colon, the expression after it is the return value — no return keyword needed.

# lambda — one expression, no name, inline double = lambda x: x * 2 double(5) # 10 add = lambda x, y: x + y add(3, 4) # 7 # equivalent named function def double(x): return x * 2

A lambda takes any number of arguments, separated by commas, and returns the result of a single expression. No return keyword — the expression is the return value.

2. Common Patterns

Lambdas appear most often as short-lived key functions passed to sorted, map, and filter — where naming the function would add noise without adding clarity.

# sorted — sort by a derived key people = [("Alice", 30), ("Bob", 25), ("Charlie", 35)] sorted(people, key=lambda p: p[1]) # [("Bob", 25), ("Alice", 30), ("Charlie", 35)] # map — transform each element nums = [1, 2, 3, 4] list(map(lambda x: x ** 2, nums)) # [1, 4, 9, 16] # filter — keep matching elements list(filter(lambda x: x % 2 == 0, nums)) # [2, 4]

sorted with a key lambda is the most common use in practice. map and filter are often replaced by list comprehensions, but lambda makes them readable for simple cases.

3. When to Use def Instead

Lambdas are limited to a single expression — no statements, assignments, or branching logic. Anything with multiple steps or reuse is cleaner as a named function.

# avoid — conditional logic in a lambda is hard to read transform = lambda x: x if x > 0 else -x # prefer def for anything with logic or reuse def abs_value(x): return x if x > 0 else -x

Use a lambda when the function is short, used once, and naming it adds no clarity. Use def when there is branching logic, multiple steps, or the function will be reused — named functions are easier to test and debug.