Advanced Iterator Techniques
Generator Expressions
Generator expressions provide a concise way to create iterators with minimal memory overhead:
## Compact iterator creation
squared_numbers = (x**2 for x in range(10))
print(list(squared_numbers)) ## [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
graph TD
A[Itertools] --> B[Infinite Iterators]
A --> C[Finite Iterators]
A --> D[Combinatoric Iterators]
Function |
Description |
Example |
itertools.count() |
Infinite counter |
count(10) |
itertools.cycle() |
Repeats sequence |
cycle([1,2,3]) |
itertools.chain() |
Combines iterators |
chain([1,2], [3,4]) |
Custom Iterator Chaining
from itertools import chain
def custom_chain_iterators(*iterators):
return chain.from_iterable(iterators)
## Example usage
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
def prime_generator():
primes = [2, 3, 5, 7, 11]
for prime in primes:
yield prime
combined_iterator = custom_chain_iterators(fibonacci(), prime_generator())
print(list(next(combined_iterator) for _ in range(10)))
Lazy Evaluation Techniques
class LazyEvaluator:
def __init__(self, data):
self._data = data
self._cache = {}
def __iter__(self):
for item in self._data:
if item not in self._cache:
self._cache[item] = self._expensive_computation(item)
yield self._cache[item]
def _expensive_computation(self, item):
## Simulate complex computation
return item * 2
def transform_iterator(iterator, transform_func):
return map(transform_func, iterator)
## Example
numbers = [1, 2, 3, 4, 5]
squared = transform_iterator(numbers, lambda x: x**2)
print(list(squared)) ## [1, 4, 9, 16, 25]
graph TD
A[Iterator Performance] --> B[Memory Efficiency]
A --> C[Lazy Evaluation]
A --> D[Reduced Computation Overhead]
Advanced Iteration Patterns
def groupby_custom(iterator, key_func):
from itertools import groupby
return {k: list(g) for k, g in groupby(sorted(iterator, key=key_func), key=key_func)}
## Example usage
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
grouped = groupby_custom(data, lambda x: x % 2 == 0)
print(grouped)
Best Practices
- Use generators for memory efficiency
- Leverage itertools for complex iterations
- Implement lazy evaluation when possible
- Cache expensive computations
LabEx recommends mastering these advanced iterator techniques to write more efficient and elegant Python code.