Practical Lambda Usage
Real-World Lambda Applications
Data Processing Scenarios
## Data transformation with lambda
data = [
{'name': 'Alice', 'age': 25},
{'name': 'Bob', 'age': 30},
{'name': 'Charlie', 'age': 22}
]
## Sort by age
sorted_data = sorted(data, key=lambda x: x['age'])
print(sorted_data)
Common Use Cases
flowchart TD
A[Lambda Use Cases] --> B[Sorting]
A --> C[Filtering]
A --> D[Data Transformation]
A --> E[Functional Programming]
1. Advanced Filtering
## Complex filtering with lambda
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
complex_filter = list(filter(lambda x: x > 5 and x % 2 == 0, numbers))
print(complex_filter) ## Output: [6, 8, 10]
2. Dynamic Function Generation
def create_multiplier(factor):
return lambda x: x * factor
double = create_multiplier(2)
triple = create_multiplier(3)
print(double(5)) ## Output: 10
print(triple(5)) ## Output: 15
Lambda in Different Contexts
Context |
Example |
Use Case |
Sorting |
sorted(list, key=lambda x) |
Custom sorting |
Mapping |
map(lambda x: transform(x), list) |
Data transformation |
Filtering |
filter(lambda x: condition(x), list) |
Selective processing |
3. Error Handling with Lambda
def safe_division(func):
return lambda x, y: func(x, y) if y != 0 else None
divide = safe_division(lambda x, y: x / y)
print(divide(10, 2)) ## Output: 5.0
print(divide(10, 0)) ## Output: None
Advanced Composition
## Function composition with lambda
def compose(f, g):
return lambda x: f(g(x))
square = lambda x: x ** 2
increment = lambda x: x + 1
square_then_increment = compose(square, increment)
print(square_then_increment(3)) ## Output: 16
import timeit
## Lambda vs traditional function
def traditional_square(x):
return x ** 2
lambda_square = lambda x: x ** 2
## Performance comparison
print(timeit.timeit('traditional_square(5)', globals=globals(), number=1000000))
print(timeit.timeit('lambda_square(5)', globals=globals(), number=1000000))
Best Practices
- Keep lambdas simple
- Use named functions for complex logic
- Prioritize readability
- Consider performance implications
LabEx Insight
At LabEx, we recommend mastering lambda functions through practical, hands-on experience and understanding their strengths and limitations.
Complex Example: Data Processing Pipeline
## Comprehensive lambda data processing
data = [
{'product': 'Laptop', 'price': 1000, 'stock': 50},
{'product': 'Phone', 'price': 500, 'stock': 100},
{'product': 'Tablet', 'price': 300, 'stock': 75}
]
## Complex filtering and transformation
discounted_products = list(
map(
lambda x: {**x, 'discounted_price': x['price'] * 0.9},
filter(lambda x: x['stock'] > 30, data)
)
)
print(discounted_products)
Conclusion
Lambda functions offer powerful, concise solutions for various programming challenges when used judiciously.