Lambda with map()
Transform sequences:
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared) # [1, 4, 9, 16, 25]
Lambda with filter()
Filter sequences:
numbers = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # [2, 4, 6]
Lambda with sorted()
Use as key function:
students = [("Alice", 25), ("Bob", 20), ("Charlie", 22)]
sorted_by_age = sorted(students, key=lambda x: x[1])
print(sorted_by_age) # [('Bob', 20), ('Charlie', 22), ('Alice', 25)]
Lambda with reduce()
Accumulate values:
from functools import reduce
numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers)
print(product) # 120
When to Use
- Simple functions: One-line operations
- Higher-order functions: map, filter, sorted
- Avoid: Complex logic or multiple statements
Best Practices
- Keep lambdas simple: Use regular functions for complex logic
- Use with built-ins: map, filter, sorted work well with lambda
- Consider comprehensions: Often more readable
- Don't overuse: Readability matters
Next Steps
Learn about comprehensions and decorators.