Practical Use Cases
Sorting Complex Data Structures
## Sorting a list of dictionaries
students = [
{'name': 'Alice', 'grade': 85},
{'name': 'Bob', 'grade': 92},
{'name': 'Charlie', 'grade': 78}
]
## Sort by grade in descending order
sorted_students = sorted(students, key=lambda x: x['grade'], reverse=True)
print(sorted_students)
Functional Programming Techniques
graph TD
A[Lambda in Functional Programming] --> B[Map]
A --> C[Filter]
A --> D[Reduce]
## Convert temperatures from Celsius to Fahrenheit
celsius_temps = [0, 10, 20, 30, 40]
fahrenheit_temps = list(map(lambda c: (c * 9/5) + 32, celsius_temps))
print(fahrenheit_temps)
Filter Operations
## Filter even numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)
Event Handling and Callbacks
## Simple event handler with lambda
class Button:
def __init__(self):
self.callback = lambda: print("Default action")
def set_action(self, action):
self.callback = action
def click(self):
self.callback()
## Usage
button = Button()
button.click() ## Default action
button.set_action(lambda: print("Custom action"))
button.click() ## Custom action
Use Case |
Lambda Pattern |
Example |
Cleaning Data |
Transformation |
lambda x: x.strip() |
Formatting |
Conversion |
lambda x: f"{x:.2f}" |
Validation |
Conditional |
lambda x: x > 0 |
Configuration and Dependency Injection
## Dynamic configuration with lambda
class ConfigManager:
def __init__(self):
self.strategies = {
'uppercase': lambda x: x.upper(),
'lowercase': lambda x: x.lower(),
'capitalize': lambda x: x.capitalize()
}
def process(self, text, strategy='uppercase'):
return self.strategies.get(strategy, lambda x: x)(text)
config = ConfigManager()
print(config.process("hello")) ## HELLO
print(config.process("world", 'capitalize')) ## World
## Caching with lambda
def memoize(func):
cache = {}
return lambda x: cache.setdefault(x, func(x))
## Expensive computation
def expensive_computation(n):
return sum(range(n))
cached_computation = memoize(expensive_computation)
print(cached_computation(1000)) ## First call computes
print(cached_computation(1000)) ## Second call uses cache
LabEx Recommendation
At LabEx, we emphasize using lambda functions judiciously, focusing on readability and maintainability.
Advanced Composition
## Function composition with lambda
def compose(*functions):
return lambda x: reduce(lambda v, f: f(v), functions, x)
## Example usage
add_10 = lambda x: x + 10
multiply_2 = lambda x: x * 2
square = lambda x: x ** 2
composed_func = compose(add_10, multiply_2, square)
print(composed_func(3)) ## (3^2 * 2) + 10
Best Practices
- Keep lambda functions simple
- Avoid complex logic in lambdas
- Use named functions for complex operations
- Consider readability over brevity