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.
Python code
15 lines"""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
[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
- Use `itertools.islice(counter, 7)` to slice the first 7 values without a comprehension
- 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
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.