Practical Iterator Patterns
Iterator Design Patterns
Iterator patterns provide structured approaches to managing and traversing collections efficiently. This section explores practical implementations and real-world scenarios.
Common Iterator Patterns
graph TD
A[Iterator Patterns] --> B[Filtering Iterator]
A --> C[Transforming Iterator]
A --> D[Chained Iterator]
A --> E[Sliding Window Iterator]
1. Filtering Iterator
class FilterIterator:
def __init__(self, iterator, predicate):
self.iterator = iterator
self.predicate = predicate
def __iter__(self):
return self
def __next__(self):
while True:
item = next(self.iterator)
if self.predicate(item):
return item
## Usage example
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = FilterIterator(iter(numbers), lambda x: x % 2 == 0)
print(list(even_numbers))
class TransformIterator:
def __init__(self, iterator, transform_func):
self.iterator = iterator
self.transform_func = transform_func
def __iter__(self):
return self
def __next__(self):
item = next(self.iterator)
return self.transform_func(item)
## Usage example
numbers = [1, 2, 3, 4, 5]
squared_numbers = TransformIterator(iter(numbers), lambda x: x ** 2)
print(list(squared_numbers))
Advanced Iterator Patterns
Sliding Window Iterator
def sliding_window(iterable, window_size):
iterator = iter(iterable)
window = []
for _ in range(window_size):
window.append(next(iterator))
yield window
for item in iterator:
window.pop(0)
window.append(item)
yield window
## Usage
data = [1, 2, 3, 4, 5, 6]
for window in sliding_window(data, 3):
print(window)
Iterator Pattern Comparison
Pattern |
Use Case |
Complexity |
Performance |
Filtering |
Selective iteration |
Low |
O(n) |
Transforming |
Data manipulation |
Low |
O(n) |
Sliding Window |
Batch processing |
Medium |
O(n) |
Chained |
Combining iterators |
Medium |
O(n) |
Practical Considerations
- Use generators for memory efficiency
- Implement lazy evaluation
- Minimize unnecessary computations
Error Handling
def safe_iterator(iterator):
try:
while True:
try:
yield next(iterator)
except ValueError as e:
print(f"Skipping invalid item: {e}")
except StopIteration:
return
LabEx Recommendation
At LabEx, we encourage developers to master iterator patterns for writing more elegant and efficient Python code.
Best Practices
- Prefer generators over complex iterator classes
- Keep iterator logic simple and focused
- Use itertools for complex iteration scenarios
- Implement proper error handling
Common Pitfalls
- Overcomplicating iterator implementations
- Ignoring memory consumption
- Neglecting error handling
- Premature optimization