PythonLambda Functions

Lambda Functions

A lambda is a small, anonymous function — one written inline, without a def statement or a name. Lambdas exist for situations where you need a short throwaway function, often passed directly as an argument to another function.

Syntax

The syntax is lambda parameters: expression. It always evaluates exactly one expression and implicitly returns its result — there is no return keyword and no function body with multiple statements.

Python
square = lambda x: x * x
add = lambda a, b: a + b

print(square(5))    # 25
print(add(3, 4))     # 7
25
7

The equivalent using def makes the comparison clear:

Python
def square(x):
    return x * x


def add(a, b):
    return a + b
The Single-Expression Limitation

A lambda body must be a single expression — no if/else statements, loops, assignments, or multiple lines. You can use a conditional expression (the ternary ... if ... else ... form) since that's still a single expression.

Python
# Valid: conditional expression, still one expression
classify = lambda n: "even" if n % 2 == 0 else "odd"
print(classify(7))
print(classify(8))

# Invalid — this would be a SyntaxError:
# broken = lambda n:
#     if n % 2 == 0:
#         return "even"
odd
even
Common Use with `sorted()`, `map()`, and `filter()`

Lambdas shine as short, inline arguments to functions that expect a function, most commonly the key= parameter of sorted(), or the mapping/filtering functions map() and filter().

Python
people = [("Ada", 36), ("Grace", 85), ("Linus", 54)]

# Sort by age (the second item of each tuple)
by_age = sorted(people, key=lambda person: person[1])
print(by_age)

# map(): square every number
squares = list(map(lambda x: x * x, [1, 2, 3, 4]))
print(squares)

# filter(): keep only even numbers
evens = list(filter(lambda x: x % 2 == 0, range(10)))
print(evens)
[('Ada', 36), ('Linus', 54), ('Grace', 85)]
[1, 4, 9, 16]
[0, 2, 4, 6, 8]

sorted(people, key=lambda person: person[1]) reads naturally: "sort people, using each person's second element as the sort key."

When Lambdas Hurt Readability
Warning
Lambdas are great for a short `key=` or `map`/`filter` callback, but stacking multiple lambdas, nesting them, or cramming complex logic into one produces code that is hard to read and impossible to name meaningfully. If a lambda needs a comment to explain it, it should probably be a named function with `def` instead.

Python
# Hard to read — what is this actually computing?
process = lambda data: [x * 2 for x in data if x > 0 and x % 2 == 0 or x < -10]

# Clearer with a named function and a docstring
def process(data):
    """Double positive even numbers, or very negative numbers."""
    return [x * 2 for x in data if (x > 0 and x % 2 == 0) or x < -10]
`def` vs `lambda`

Aspect

def function

lambda function

Name

Named (unless assigned anonymously)

Anonymous by default

Body

Any number of statements

Exactly one expression

Return

Explicit return (or implicit None)

Implicit — the expression's value

Docstring

Supported

Not supported

Best for

Reusable, documented, complex logic

Short, inline, throwaway callbacks

Debuggability

Named in tracebacks

Shows as <lambda> in tracebacks

Tip
A useful rule of thumb: if you would want to give the function a name to explain what it does, just use `def` and give it that name. Reserve `lambda` for cases where the function truly is disposable and its purpose is obvious from context (like a sort key).
Example
Sorting a list of dictionaries by multiple criteria using a lambda that returns a tuple — a common real-world pattern.

Python
students = [
    {"name": "Ada", "grade": 90},
    {"name": "Grace", "grade": 95},
    {"name": "Linus", "grade": 90},
]

# Sort by grade descending, then name ascending for ties
ranked = sorted(students, key=lambda s: (-s["grade"], s["name"]))
for student in ranked:
    print(student["name"], student["grade"])
Grace 95
Ada 90
Linus 90
Note
Lambdas can also be assigned to a variable, as shown earlier (`square = lambda x: x * x`), but most style guides (including PEP 8) discourage this — if it's worth naming, it's worth writing as a proper `def` function.