INSIGHTS
Software Development

Python Fibonacci Sequence Tutorial: Generate and Optimize Fibonacci Series

In this article
  1. Generate the first n numbers iteratively
  2. Compute F(n) without storing the whole sequence
  3. Use caching when recursion serves the lesson
  4. Stream an unbounded sequence with a generator
  5. Avoid unreliable formula shortcuts
  6. Tests and common mistakes

The Fibonacci numbers follow the rule F(0)=0, F(1)=1 and F(n)=F(n-1)+F(n-2) for integers n >= 2. For example, the first ten values are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34. A useful Python tutorial should explain both how to generate the sequence and how to choose an implementation that does not waste time or memory.

Generate the first n numbers iteratively

def fibonacci_sequence(count: int) -> list[int]:
    if count < 0:
        raise ValueError("count must be nonnegative")
    result = []
    a, b = 0, 1
    for _ in range(count):
        result.append(a)
        a, b = b, a + b
    return result

print(fibonacci_sequence(10))
# [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

The loop executes once per requested value, so its time complexity is O(n). The resulting list uses O(n) space, ignoring the growing size of large integers. A count of zero returns an empty list. The two-variable update makes the recurrence visible without recursion or complex indexing.

Compute F(n) without storing the whole sequence

def fibonacci_number(n: int) -> int:
    if n < 0:
        raise ValueError("n must be nonnegative")
    a, b = 0, 1
    for _ in range(n):
        a, b = b, a + b
    return a

assert fibonacci_number(0) == 0
assert fibonacci_number(1) == 1
assert fibonacci_number(10) == 55

This version does O(n) loop iterations and keeps only the current pair, so auxiliary storage is constant, again excluding the integer-size cost. Returning the nth value and returning the first n values are different tasks: fibonacci_sequence(10) ends at 34, while fibonacci_number(10) returns 55.

Use caching when recursion serves the lesson

from functools import lru_cache

@lru_cache(maxsize=None)
def fibonacci_cached(n: int) -> int:
    if n < 0:
        raise ValueError("n must be nonnegative")
    if n < 2:
        return n
    return fibonacci_cached(n - 1) + fibonacci_cached(n - 2)

print(fibonacci_cached(10))  # 55

Caching prevents repeated computation of the same subproblems. Without caching, naive recursion has exponential call growth; with caching, the function computes each needed value once. It uses memory for cached results and recursive calls. A very large n can still encounter Python’s recursion limit, making iteration the simpler default. Caching is a teaching tool here, not a reason to prefer recursion for every numeric task.

Stream an unbounded sequence with a generator

from itertools import islice

def fibonacci_numbers():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

print(list(islice(fibonacci_numbers(), 8)))
# [0, 1, 1, 2, 3, 5, 8, 13]

The generator yields one value at a time and remembers a and b between requests. islice places an explicit limit on consumption; calling list(fibonacci_numbers()) without a limit would never finish. Generators reduce collection storage when the caller consumes values incrementally, but they do not make arbitrarily large Fibonacci integers cheap to compute.

Avoid unreliable formula shortcuts

Binet’s closed form uses floating-point approximations involving the square root of five. Rounding may look correct for small indices, but ordinary floating-point arithmetic loses exactness as integers grow. Python already supports exact arbitrary-precision integers, so iterative or properly designed integer algorithms are safer when correct values matter. “Backtracking” is not a typical or beneficial Fibonacci generation method; do not add it as a supposed optimization.

Tests and common mistakes

  • Test boundary values n=0, n=1, and a typical input such as n=10.
  • Distinguish a function that returns the nth value from one that generates n values.
  • Reject negative counts rather than returning a plausible-looking empty sequence.
  • Measure real performance for repeated queries before replacing a simple loop with caching or a more advanced doubling algorithm.

Fibonacci is an accessible way to compare lists, loops, recursion and generators. For related Python collection behavior, consult Python operators and data structures. The Python control-flow documentation also illustrates loops and function definitions used in these implementations.

Filed under Software Development