Lambda Use Cases
Functional Programming Techniques
Map Function
## Transforming list elements
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
print(squared) ## Output: [1, 4, 9, 16, 25]
Filter Function
## Filtering list elements
ages = [12, 18, 25, 30, 45, 50]
adults = list(filter(lambda x: x >= 18, ages))
print(adults) ## Output: [18, 25, 30, 45, 50]
Reduce Function
from functools import reduce
## Calculating product of list elements
numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers)
print(product) ## Output: 120
Sorting and Comparison
Complex Sorting
## Sorting complex data structures
students = [
{'name': 'Alice', 'grade': 85},
{'name': 'Bob', 'grade': 92},
{'name': 'Charlie', 'grade': 78}
]
## Sort by grade
sorted_students = sorted(students, key=lambda student: student['grade'])
Event Handling and Callbacks
flowchart TD
A[Lambda in Event Handling] --> B[GUI Programming]
A --> C[Callback Functions]
A --> D[Asynchronous Programming]
Tkinter GUI Example
import tkinter as tk
root = tk.Tk()
button = tk.Button(root, text="Click me",
command=lambda: print("Button clicked!"))
button.pack()
Dictionary Manipulation
## Transform dictionary
prices = {'apple': 0.5, 'banana': 0.3, 'orange': 0.6}
discounted_prices = {k: v * 0.9 for k, v in prices.items()}
Use Case |
Pros |
Cons |
Simple Transformations |
Concise |
Limited Complexity |
Functional Operations |
Readable |
Performance Overhead |
Inline Functions |
Quick Implementation |
Reduced Debugging |
Advanced Scenarios
Decorators with Lambda
def logger(func):
return lambda *args: (print(f"Calling {func.__name__}"), func(*args))
@logger
def add(x, y):
return x + y
Best Practices
- Use lambda for short, simple operations
- Prefer named functions for complex logic
- Consider readability and maintainability
Note: At LabEx, we emphasize understanding lambda functions as a powerful yet nuanced Python programming technique.