Iterator Patterns
Advanced Iterator Design Strategies
Iterator patterns provide sophisticated approaches to managing complex iteration scenarios in Python, enabling more flexible and powerful data processing techniques.
Sentinel Iterator Pattern
The sentinel iterator pattern allows controlled iteration with a termination condition:
def read_until_sentinel(file, sentinel='END'):
for line in file:
line = line.strip()
if line == sentinel:
break
yield line
## Usage example
with open('data.txt', 'r') as file:
for data in read_until_sentinel(file):
print(data)
Chained Iterator Pattern
Combine multiple iterators into a single sequence:
from itertools import chain
def chained_iterators():
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = [7, 8, 9]
return chain(list1, list2, list3)
## Seamless iteration across multiple collections
for item in chained_iterators():
print(item)
Iterator Composition Patterns
graph TD
A[Iterator Patterns] --> B[Sentinel Iterator]
A --> C[Chained Iterator]
A --> D[Filtered Iterator]
A --> E[Transformed Iterator]
Filtered Iterator Pattern
Create iterators with dynamic filtering capabilities:
def filtered_iterator(data, condition):
return filter(condition, data)
## Example usage
numbers = range(1, 11)
even_numbers = filtered_iterator(numbers, lambda x: x % 2 == 0)
print(list(even_numbers))
Pattern |
Description |
Example |
Map Iterator |
Transform each element |
map(lambda x: x**2, [1,2,3]) |
Filter Iterator |
Select elements |
filter(lambda x: x > 5, [1,6,3,8]) |
Reduce Iterator |
Aggregate elements |
functools.reduce(lambda x,y: x+y, [1,2,3]) |
Infinite Iterator Pattern
Create iterators that generate sequences indefinitely:
from itertools import count, cycle
## Infinite counter
def infinite_counter():
for num in count(1):
yield num
## Cyclic iterator
def cyclic_sequence():
return cycle([1, 2, 3])
## Demonstrate first few elements
counter = infinite_counter()
print([next(counter) for _ in range(5)])
Memory-Efficient Iteration Techniques
def memory_efficient_processing(large_dataset):
for item in large_dataset:
## Process item without loading entire dataset
processed_item = item.transform()
yield processed_item
## Example usage with generator
result = memory_efficient_processing(large_data_source)
Advanced Iterator Composition
Combine multiple iterator patterns for complex data processing:
def advanced_iterator_pipeline(data):
return (
x for x in data ## Base iterator
if x % 2 == 0 ## Filter even numbers
)
numbers = range(1, 20)
processed = advanced_iterator_pipeline(numbers)
print(list(processed))
Best Practices
- Use iterator patterns for memory efficiency
- Leverage built-in iterator tools
- Implement lazy evaluation techniques
- Consider performance implications
By mastering these iterator patterns, developers can create sophisticated data processing solutions in LabEx Python programming environments.