Advanced Iterator Patterns
Iterator Composition Techniques
Chaining Iterators
from itertools import chain
def chain_iterators():
iter1 = iter([1, 2, 3])
iter2 = iter([4, 5, 6])
combined = chain(iter1, iter2)
return list(combined)
print(chain_iterators()) ## [1, 2, 3, 4, 5, 6]
graph TD
A[Source Iterator] --> B[Transformation]
B --> C[Transformed Iterator]
Map and Filter Iterators
def transform_iterator():
numbers = range(10)
squared = map(lambda x: x**2, numbers)
even_squared = filter(lambda x: x % 2 == 0, squared)
return list(even_squared)
print(transform_iterator()) ## [0, 4, 16, 36, 64]
Custom Iterator Decorators
Decorator Type |
Purpose |
Example |
Filtering |
Select specific elements |
filter() |
Mapping |
Transform elements |
map() |
Reducing |
Aggregate elements |
functools.reduce() |
Advanced Iterator Techniques
Iterator Multiplication
from itertools import tee
def split_iterator(iterator, n):
return tee(iterator, n)
source = iter([1, 2, 3, 4])
iter1, iter2 = split_iterator(source, 2)
print(list(iter1)) ## [1, 2, 3, 4]
print(list(iter2)) ## [1, 2, 3, 4]
Lazy Evaluation Patterns
def lazy_fibonacci():
def generate():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
return (x for x in generate())
fib = lazy_fibonacci()
limited_fib = list(next(fib) for _ in range(10))
print(limited_fib)
Iterator State Management
Stateful Iterators
class StatefulIterator:
def __init__(self, data):
self.data = data
self.index = 0
self.state = {}
def __iter__(self):
return self
def __next__(self):
if self.index < len(self.data):
current = self.data[self.index]
self.state[self.index] = current
self.index += 1
return current
raise StopIteration
- Use generators for memory efficiency
- Prefer lazy evaluation
- Minimize unnecessary iterations
Complex Iterator Composition
from itertools import islice, cycle
def complex_iterator_pattern():
infinite_cycle = cycle([1, 2, 3])
limited_cycle = islice(infinite_cycle, 10)
return list(limited_cycle)
print(complex_iterator_pattern()) ## [1, 2, 3, 1, 2, 3, 1, 2, 3, 1]
Learning with LabEx
At LabEx, we recommend exploring advanced iterator patterns through progressive coding challenges that enhance your understanding of Python's iteration mechanisms.
Best Practices
- Understand lazy evaluation principles
- Use built-in iterator tools
- Create modular, reusable iterator designs