Introduction
Lambda functions are small anonymous functions defined with the lambda keyword.
Basic Syntax
# Lambda function
square = lambda x: x ** 2
print(square(5)) # 25
# Multiple arguments
add = lambda x, y: x + y
print(add(3, 4)) # 7
# No arguments
get_pi = lambda: 3.14159
Common Use Cases
# Sorting
students = [("Alice", 85), ("Bob", 92), ("Charlie", 78)]
students.sort(key=lambda x: x[1]) # Sort by grade
# Map
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
# Filter
evens = list(filter(lambda x: x % 2 == 0, numbers))
# Reduce
from functools import reduce
product = reduce(lambda x, y: x * y, numbers)
Lambda vs Regular Functions
| Aspect | Lambda | Regular Function |
|---|---|---|
| Syntax | Single expression | Multiple statements |
| Name | Anonymous | Named |
| Return | Implicit | Explicit |
| Use case | Short operations | Complex logic |
Practice Problems
- Use lambda with sorted() for custom sorting
- Create lambda functions for mathematical operations
- Use map() with lambda for data transformation
- Filter a list of dictionaries using lambda
- Combine lambda with reduce() for aggregation