Python Lambda Functions โ Knowledge Base Article
Source: Tech With Tim โ YouTube tutorial
URL: https://www.youtube.com/watch?v=HQNiSfb795A
Tags: #python #lambda #functional-programming #beginner
1. What Is a Lambda Function?
A lambda function is a small, anonymous, inline function defined in a single expression.
- Anonymous: does not require a name (though you can assign it to a variable).
- Single expression: the expression after the colon is automatically returned โ no
returnkeyword needed. - Any number of parameters: comma-separated like a normal function.
Equivalent named function
Both definitions above produce the same result. The lambda is preferred when you only need the function once and want to keep the definition local.
2. Why Use Lambdas?
Use lambdas when you need to pass a short, one-off function as an argument to another function โ typically map(), filter(), sorted(), or reduce().
Rule of thumb: if the logic fits on one line and you won't reuse the function elsewhere, use a lambda.
3. Common Use Cases
3.1 map() โ Apply a function to every element
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
squared = list(map(lambda x: x ** 2, numbers))
# โ [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Without a lambda you'd need a separate def square(x): return x**2, which is redundant if you only use it here.
3.2 filter() โ Keep elements that satisfy a condition
The lambda returns True for even numbers โ those are kept; False โ rejected.
3.3 sorted() โ Custom sort key
data = [(1, 'c'), (2, 'a'), (3, 'b')]
sorted_by_letter = sorted(data, key=lambda x: x[1])
# โ [(2, 'a'), (3, 'b'), (1, 'c')]
The key function extracts the second element (index 1) from each tuple, and Python sorts by that value.
Multi-level sort (secondary key on tie):
3.4 reduce() โ Fold an iterable to a single value
from functools import reduce
numbers = [1, 2, 3, 4, 5]
total = reduce(lambda acc, x: acc + x, numbers)
# โ 15
How it works step-by-step:
1. acc = 1 (first element), x = 2 โ return 3
2. acc = 3, x = 3 โ return 6
3. acc = 6, x = 4 โ return 10
4. acc = 10, x = 5 โ return 15
Find the maximum with reduce:
4. Advanced / Oddball Syntax
Immediately Invoked Lambda
You can define and call a lambda on the same line (valid Python, but rarely practical):
The function is defined, then called immediately with (3, 5). Technically valid โ just don't do it in production code without a good reason.
5. When NOT to Use a Lambda
Use def (named function) when... |
Use lambda when... |
|---|---|
| Logic spans multiple lines | Logic fits one expression |
| You need docstrings / annotations | It's a throwaway callback |
| The function is reused in several places | Used once as an argument |
| Debugging โ named functions have clearer tracebacks | The function is trivial (< 80 chars) |
6. Quick Reference
| Syntax | lambda <params>: <expression> |
|---|---|
| Parameters | Any number (zero, one, many, defaults, *args, **kwargs) |
| Return | The expression value (implicit) |
| Restrictions | Single expression only โ no statements (return, if/elif blocks, loops, assert) |
| Common friends | map(), filter(), sorted(key=...), reduce() |
| Module needed for reduce | from functools import reduce |
7. Summary
- Lambdas are inline anonymous functions โ one expression, auto-return.
- Use them when passing a simple one-off function to
map,filter,sorted, orreduce. - Anything complex โ use
def. Lambdas trade readability for conciseness; don't overuse them.