How to Create an Infinite Arithmetic Sequence Generator in Python

Build a memory-efficient generator that yields an infinite arithmetic progression and extract the first N values with list comprehension.

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

Python code

15 lines
Python 3.9+
"""Count generator infinite arithmetic progression"""


def arithmetic_counter(start=0, step=1):
    """Generate an infinite arithmetic sequence."""
    current = start
    while True:
        yield current
        current += step


if __name__ == "__main__":
    counter = arithmetic_counter(1, 3)
    result = [next(counter) for _ in range(7)]
    print(result)

Output

stdout
[1, 4, 7, 10, 13, 16, 19]

How it works

The yield keyword turns the function into a generator, allowing it to produce values lazily without storing the entire sequence in memory. The while True loop keeps the progression running indefinitely, but next() only pulls one value at a time, so the list comprehension grabs exactly seven numbers. Each call to next() resumes the generator right after the previous yield, incrementing current by the step value. This pattern is ideal for handling potentially unlimited sequences without exhausting system resources.

Common mistakes

  • Trying to convert the entire generator to a list with `list(counter)` — this hangs forever
  • Forgetting that generators are iterators and can only be consumed once
  • Using `range()` with a large upper bound instead of a lazy generator for potentially infinite data
  • Not catching `StopIteration` when manually calling `next()` too many times

Variations

  1. Use `itertools.islice(counter, 7)` to slice the first 7 values without a comprehension
  2. Pass custom `start` and `step` arguments to create any arithmetic sequence, like even numbers with `(2, 2)`

Real-world use cases

  • Generating sequential transaction IDs or invoice numbers without storing a full list.
  • Producing heartbeat or ping data for monitoring systems at regular intervals.
  • Creating pagination cursors or offset values for API requests that need unlimited increments.

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.