Advanced Iterator Techniques
Generator Iterators
Generators provide a powerful way to create iterators with minimal code:
def fibonacci_generator(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
fib_iter = fibonacci_generator(10)
list(fib_iter) ## [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Iterator Composition Techniques
1. Iterator Chaining
from itertools import chain
def combine_iterators():
iter1 = range(3)
iter2 = range(3, 6)
combined = chain(iter1, iter2)
return list(combined) ## [0, 1, 2, 3, 4, 5]
2. Custom Iterator Composition
class CompositeIterator:
def __init__(self, *iterators):
self.iterators = list(iterators)
def __iter__(self):
return self
def __next__(self):
while self.iterators:
try:
return next(self.iterators[0])
except StopIteration:
self.iterators.pop(0)
raise StopIteration
Advanced Iterator Methods
Method |
Description |
Example |
itertools.cycle() |
Infinite iterator |
cycle([1,2,3]) |
itertools.islice() |
Slice iterators |
islice(range(10), 2, 8) |
itertools.tee() |
Multiple iterator copies |
tee(range(5), 3) |
graph TD
A[Input Iterator] --> B[Transformation Function]
B --> C{Condition Met?}
C -->|Yes| D[Yield Transformed Item]
C -->|No| E[Skip Item]
D --> F{More Items?}
F -->|Yes| B
F -->|No| G[End Iteration]
Lazy Evaluation Techniques
def lazy_map(func, iterator):
for item in iterator:
yield func(item)
## Efficient memory processing
processed = lazy_map(lambda x: x**2, range(1000000))
Context Managers for Iterators
class ManagedIterator:
def __init__(self, data):
self.data = iter(data)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
## Cleanup logic
del self.data
def __iter__(self):
return self
def __next__(self):
return next(self.data)
- Use generators for memory efficiency
- Implement lazy evaluation
- Avoid unnecessary list conversions
- Use
itertools
for complex iterations
LabEx Recommendation
Explore advanced iterator techniques in LabEx Python environments to write more efficient and elegant code, leveraging Python's powerful iteration capabilities.