Infinite Iterators
Lesson 6 of 13 in Coddy's Python Iterators course.
Infinite iterators are a special type of iterator in Python that can potentially generate an endless sequence of values. Unlike finite iterators that eventually raise a StopIteration exception, infinite iterators continue to produce values indefinitely.
Characteristics of Infinite Iterators
- They never raise a
StopIterationexception. - They can be useful for generating continuous sequences or simulating endless streams of data.
- Care must be taken to avoid infinite loops when using them.
Creating an Infinite Iterator
Here's a simple example of an infinite iterator that generates an endless sequence of integers:
class InfiniteCounter:
def __init__(self, start=0):
self.count = start
def __iter__(self):
return self
def __next__(self):
current = self.count
self.count += 1
return current
# Usage
counter = InfiniteCounter()
for i in counter:
print(i)
if i >= 5:
break # Prevent infinite loop
In this example, the InfiniteCounter class will keep generating numbers indefinitely. We use a break statement to stop the iteration after a certain condition is met.
Built-in Infinite Iterators
Python's itertools module provides several useful infinite iterators:
itertools.count(start, step): Counts up infinitely from a start valueitertools.cycle(iterable): Cycles through an iterable indefinitelyitertools.repeat(elem, [n]): Repeats an element indefinitely or n times
Example using itertools.count():
from itertools import count
for i in count(10):
print(i)
if i >= 15:
break
# Outputs: 10, 11, 12, 13, 14, 15
Cautions and Best Practices
- Always have a way to break out of loops involving infinite iterators to prevent program hang.
- Use infinite iterators judiciously and only when necessary.
- Consider using generator functions for more memory-efficient infinite sequences.
Infinite iterators provide a powerful tool for scenarios requiring continuous data generation or processing, but they should be used carefully to ensure your program behaves as expected.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyCreate an infinite iterator class called CyclicCounter that cycles through a given range of numbers indefinitely. The iterator should start from a specified number and cycle back to it after reaching the end of the range.
You are provided with the following:
- Two integers as input:
startandend(inclusive)
Your CyclicCounter class should:
- Implement the
__iter__()and__next__()methods - Generate numbers from
starttoend(inclusive) - After reaching
end, cycle back tostartand continue indefinitely
After implementing the CyclicCounter class, create an instance of it using the input values. Then, use a loop to print the first 10 numbers generated by the iterator, each on a new line.
The input will be provided as two space-separated integers representing start and end.
Try it yourself
# Read input
start, end = map(int, input().split())
class CyclicCounter:
def __init__(self, start, end):
self.start = start
self.end = end
self.current = start
def __iter__(self):
return self
# TODO: Implement the __next__() method
# Create an instance of CyclicCounter
counter = CyclicCounter(start, end)
# TODO: Use a loop to print the first 10 numbers generated by the iterator
# Remember to print each number on a new line