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.
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:
def square(x):
return x * x
def add(a, b):
return a + bThe 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.
# 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().
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
# 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 |
|
|
|---|---|---|
Name | Named (unless assigned anonymously) | Anonymous by default |
Body | Any number of statements | Exactly one expression |
Return | Explicit | 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 |
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