Skip to content

S2Q1 · Check for Arithmetic Progression

⚡ Quick Reference

Function: is_arithmetic_progression(sequence: list) -> bool

Core idea: compute the common difference from the first two elements, then verify all consecutive pairs have the same difference.

def is_arithmetic_progression(sequence: list) -> bool:
    if len(sequence) <= 1:
        return True
    diff = sequence[1] - sequence[0]
    return all(sequence[i] - sequence[i-1] == diff
               for i in range(2, len(sequence)))

Key rules: - Sequences of length 0 or 1 are trivially AP - Compute diff = sequence[1] - sequence[0] - All consecutive differences must equal diff


Problem Statement

Problem

Write a function is_arithmetic_progression(sequence) that returns True if consecutive differences are all equal.

Examples:

Input
[1, 3, 5, 7, 9]
Output
True
Input
[9, 6, 3, 0, -3, -6]
Output
True
Input
[1, 3, 5, 6, 11]
Output
False

Tracing all examples

Sequence diff All equal? Result
[1,3,5,7,9] 2 2,2,2,2 ✅ True
[2,4,6,8,10] 2 2,2,2,2 ✅ True
[9,6,3,0,-3,-6] -3 -3,-3,-3,-3,-3 ✅ True
[1,3,5,6,11] 2 2,2,1,5 ❌ False
[0,0,0,0,0] 0 0,0,0,0 ✅ True
[1,2,4,8,16] 1 1,2,4,8 ❌ False

Solution approaches

def is_arithmetic_progression(sequence: list) -> bool:
    if len(sequence) <= 1:
        return True
    diff = sequence[1] - sequence[0]
    return all(sequence[i] - sequence[i-1] == diff
               for i in range(2, len(sequence)))
def is_arithmetic_progression(sequence: list) -> bool:
    if len(sequence) <= 1:
        return True
    diffs = [b - a for a, b in zip(sequence, sequence[1:])]
    return len(set(diffs)) == 1

zip(sequence, sequence[1:]) generates all adjacent pairs. Computing their differences and checking if they all reduce to a single value confirms an AP.

def is_arithmetic_progression(sequence: list) -> bool:
    if len(sequence) <= 1:
        return True
    diff = sequence[1] - sequence[0]
    for i in range(2, len(sequence)):
        if sequence[i] - sequence[i-1] != diff:
            return False
    return True
is_arithmetic_progression = lambda seq: (
    len(seq) <= 1 or
    len(set(b - a for a, b in zip(seq, seq[1:]))) == 1
)

Key takeaways

01

Compute diff from first pair, check all others

diff = sequence[1] - sequence[0] establishes the expected common difference. Then verify every subsequent pair matches. This is O(n) - one pass through the sequence.

02

set(diffs) == 1 element - elegant check

If all differences are the same, the set of differences has exactly one element. len(set(diffs)) == 1 is a clean alternative that doesn't need to extract the first difference separately.

03

Handle length 0 and 1 as edge cases

A sequence with 0 or 1 element has no pairs to compare - it's trivially an AP. Without this guard, sequence[1] - sequence[0] would raise an IndexError on short sequences.