Applying Custom Iteration Patterns
Now that you understand how to create custom iterators, let's explore some practical applications and use cases.
Infinite Sequences
One common use case for custom iterators is to create infinite sequences, such as the Fibonacci sequence or a sequence of prime numbers. Here's an example of a Fibonacci sequence generator:
def fibonacci_generator():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
You can use this generator to iterate over the Fibonacci sequence:
fib = fibonacci_generator()
for _ in range(10):
print(next(fib)) ## Output: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
Lazy Evaluation
Custom iterators can also be used to implement lazy evaluation, where data is generated on-the-fly as it's needed, rather than all at once. This can be particularly useful when working with large or infinite data sets. Here's an example of a lazy range generator:
class LazyRange:
def __init__(self, start, stop, step=1):
self.start = start
self.stop = stop
self.step = step
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current < self.stop:
current = self.current
self.current += self.step
return current
else:
raise StopIteration()
You can use this LazyRange
class to create a range-like iterator that only generates values as they are needed:
large_range = LazyRange(0, 1_000_000_000)
for num in large_range:
if num % 1_000_000 == 0:
print(num)
This approach can be more memory-efficient than generating the entire range upfront, especially for very large data sets.
Composing Iterators
Custom iterators can also be composed to create more complex iteration patterns. For example, you could create an iterator that generates a sequence of Fibonacci numbers up to a certain limit:
def limited_fibonacci_generator(limit):
fib = fibonacci_generator()
while True:
num = next(fib)
if num > limit:
break
yield num
This limited_fibonacci_generator()
function combines the fibonacci_generator()
from the previous example with a limit check to create a new iterator that generates Fibonacci numbers up to a specified limit.
By mastering the creation and application of custom iteration patterns, you can unlock powerful and flexible ways to work with data in your Python programs.