Lambda Functions
A Lambda Function is a small, anonymous function defined without a name. While standard functions are defined using the def keyword, lambdas use the lambda keyword.
In Python, lambdas are a “syntactic sugar” for creating simple, one-off functions, primarily used as arguments for higher-order functions.
1. Syntax & Restrictions
Section titled “1. Syntax & Restrictions”Syntax: lambda arguments: expression
The Rules of Lambda
Section titled “The Rules of Lambda”- Anonymous: They don’t have a name unless you assign them to a variable.
- Single Expression: A lambda can only contain one expression. It cannot contain statements (like
if-elseblocks,forloops, orreturn). - Implicit Return: The result of the expression is automatically returned.
# Standarddef square(x): return x * x
# Lambdasq = lambda x: x * x2. Functional Patterns: Map, Filter, and Sort
Section titled “2. Functional Patterns: Map, Filter, and Sort”Lambdas shine when passed into functions that expect another function as an argument.
Case A: Custom Sorting
Section titled “Case A: Custom Sorting”You can tell the .sort() method exactly how to compare items.
data = [("Alice", 88), ("Bob", 95), ("Charlie", 82)]
# Sort by the score (index 1 of the tuple)data.sort(key=lambda item: item[1])# Result: [('Charlie', 82), ('Alice', 88), ('Bob', 95)]Case B: map() and filter()
Section titled “Case B: map() and filter()”map(): Applies the lambda to every item in an iterable.filter(): Keeps only items where the lambda returnsTrue.
nums = [1, 2, 3, 4, 5]
evens = list(filter(lambda x: x % 2 == 0, nums))squares = list(map(lambda x: x ** 2, nums))3. Under the Hood: Function Objects
Section titled “3. Under the Hood: Function Objects”Is a lambda different from a normal function? No.
When Python executes a lambda expression, it creates a standard Function Object in memory, exactly like def does. You can even inspect its properties:
f = lambda x: x + 1print(type(f)) # <class 'function'>print(f.__name__) # <lambda>The only difference is that the __name__ attribute is set to <lambda> and the object doesn’t have a docstring or type annotations.
4. The “Anti-Pattern” Warning
Section titled “4. The “Anti-Pattern” Warning”While lambdas are powerful, they are often overused by beginners.
5. Summary Table
Section titled “5. Summary Table”| Feature | def Function | lambda Function |
|---|---|---|
| Syntax | Multi-line. | Single-line expression. |
| Name | Explicitly named. | Anonymous. |
| Capability | Any statement/logic. | Expression only. |
| Return | Requires return. | Implicit return. |
| Docstrings | Supported. | Not supported. |
| Tracebacks | Shows function name. | Shows <lambda>. |