How to Generate an Arithmetic Progression List in Python

Generates a list of terms in an arithmetic progression using a list comprehension.

Easy Python 3.9+ Aug 9, 2026 Algorithms & data structures 14 views 0 copies

Python code

8 lines
Python 3.9+
def generate_ap(start, difference, count):
    """Generate a list of n terms in an arithmetic progression."""
    return [start + i * difference for i in range(count)]


if __name__ == "__main__":
    ap = generate_ap(3, 5, 6)
    print(ap)

Output

stdout
[3, 8, 13, 18, 23, 28]

How it works

The list comprehension [start + i * difference for i in range(count)] computes each term by adding i times the difference to the starting value. range(count) produces indices from 0 to count-1, so no off-by-one errors occur. This approach is concise, readable, and leverages Python's efficient list-building syntax.

Common mistakes

  • Using `range(1, count+1)` instead of `range(count)` which shifts the sequence incorrectly
  • Confusing arithmetic progression with geometric progression by multiplying instead of adding
  • Not handling negative differences which are perfectly valid in an AP

Variations

  1. Use a generator expression with `yield` for memory-efficient generation of large sequences
  2. Use `numpy.arange(start, start + count * difference, difference)` for scientific computing with arrays

Real-world use cases

  • Generating evenly spaced time steps for simulation or sampling intervals in data analysis
  • Creating axis tick positions for custom data visualizations where intervals must be uniform
  • Producing training data with linear patterns for testing machine learning regression models

Sponsored

Run this sample

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

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.