Generator Function to Yield an Infinite Counter in Python
This code demonstrates a generator function that yields an infinite sequence of integers starting from a given value, allowing lazy, memory-efficient iteration.
Python code
10 linesdef infinite_counter(start=0):
count = start
while True:
yield count
count += 1
if __name__ == "__main__":
counter = infinite_counter(5)
for _ in range(5):
print(next(counter))
Output
5
6
7
8
9
How it works
A generator function uses the yield keyword, which pauses execution and returns a value each time next() is called. The while True loop makes the generator produce values indefinitely, but because it's lazy, it only generates numbers as requested. When the generator is exhausted (which doesn't happen here), it raises StopIteration. This pattern is ideal for streams of data that would be too large to store in memory. The if __name__ == "__main__" guard ensures the test code only runs when the script is executed directly, not when imported.
Common mistakes
- Forgetting to call `next()` and trying to print the generator object directly, which shows a memory address instead of values.
- Using `yield` inside a regular function without a loop, so it only yields a single value.
- Not handling the infinite nature — using `for` without a break on the generator will run forever.
Variations
- Use the `itertools.count()` function from the standard library to achieve the same effect with less custom code.
- Add a `step` parameter to control the increment between yields.
Real-world use cases
- Creating unique sequential IDs for database records without persisting a counter.
- Feeding a data pipeline with an endless stream of monotonically increasing timestamps for simulation.
- Assigning ticket numbers or order numbers in a service that never restarts its counter.
Sponsored
More from Comprehensions & generators
- Batch Rows in Chunks with a Generator in Python easy
- Build a Generator Pipeline in Python: Filter Then Map medium
- Build a lazy generator to read file lines in Python easy
- Chunk an Iterable into Batches with a Generator in Python easy
- Convert Data in Python with Comprehensions and Generators easy
- Count Data in Python with Comprehensions and Generators easy
Keep learning
Related tutorials and quizzes for this topic.