Functional transformations in Python leverage built-in functions and functional programming concepts to manipulate lists efficiently and elegantly.
1. map() Function
## Transforming list elements using map()
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared) ## Output: [1, 4, 9, 16, 25]
2. filter() Function
## Filtering list elements
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) ## Output: [2, 4, 6, 8, 10]
Advanced Functional Techniques
3. reduce() Function
from functools import reduce
## Calculating sum using reduce()
numbers = [1, 2, 3, 4, 5]
total = reduce(lambda x, y: x + y, numbers)
print(total) ## Output: 15
Method |
Purpose |
Complexity |
Performance |
map() |
Transform elements |
Low |
High |
filter() |
Select elements |
Low |
High |
reduce() |
Aggregate elements |
Medium |
Medium |
flowchart TD
A[Input List] --> B[Functional Transformation]
B --> C{Transformation Type}
C --> D[map: Element Modification]
C --> E[filter: Element Selection]
C --> F[reduce: Element Aggregation]
D,E,F --> G[Result List/Value]
## Complex transformation with lambda
data = [1, 2, 3, 4, 5]
transformed = list(map(lambda x: x**2 if x % 2 == 0 else x, data))
print(transformed) ## Output: [1, 4, 3, 16, 5]
- Functional transformations are memory-efficient
- Suitable for large datasets
- Provide clean, readable code
LabEx Recommendation
LabEx suggests practicing functional transformations to develop more pythonic coding skills.
Best Practices
- Use lambda for simple transformations
- Prefer comprehensions for complex logic
- Consider generator expressions for large datasets
- Combine multiple functional methods when needed
Combining Functional Methods
## Chaining functional transformations
from functools import reduce
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result = reduce(
lambda x, y: x + y,
filter(lambda n: n % 2 == 0,
map(lambda x: x**2, numbers))
)
print(result) ## Output: 220