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.

Easy Python 3.9+ Aug 9, 2026 Comprehensions & generators 14 views 0 copies

Python code

10 lines
Python 3.9+
def 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

stdout
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

  1. Use the `itertools.count()` function from the standard library to achieve the same effect with less custom code.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Comprehensions & generators

Related tutorials and quizzes for this topic.