How to Generate a Geometric Progression List in Python
This Python function builds a list of n terms in a geometric progression, starting with a given first term and multiplying by a constant ratio at each step.
Python code
17 linesdef geometric_progression(first_term, ratio, count):
"""
Generate a list of 'count' terms in a geometric progression
starting with 'first_term' and multiplied by 'ratio' each step.
"""
progression = []
current = first_term
for _ in range(count):
progression.append(current)
current *= ratio
return progression
if __name__ == "__main__":
# Example: first term 2, ratio 3, 6 terms
result = geometric_progression(2, 3, 6)
print(result)
Output
[2, 6, 18, 54, 162, 486]
How it works
The function initializes an empty list and a current variable set to first_term. It loops count times, appending the current term to the list and then multiplying current by ratio. This builds the progression incrementally. The loop runs exactly count times, so the list length matches the requested number of terms. Since integers are used, the output remains exact without floating-point rounding issues.
Common mistakes
- Forgetting to multiply by the ratio after the first term, producing a constant list.
- Using `range(count + 1)` which yields one extra term.
- Assuming the ratio or first term must be integers, but they can be floats.
- Not handling non‑positive `count` gracefully; the function returns an empty list.
Variations
- Use a generator expression with `itertools.islice` to lazily produce terms.
- Use a list comprehension with the exponent formula: `[first_term * ratio**i for i in range(count)]`.
Real-world use cases
- Generating compound interest calculations where each period multiplies a balance by a fixed rate.
- Producing population growth models for biological or ecological simulations.
- Creating exponential backoff delays for retry logic in distributed systems.
Sponsored
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.