How to Generate Fibonacci Numbers in Python Without Recursion

Build an efficient infinite Fibonacci sequence using a generator function with O(1) memory and no recursion overhead.

Easy Python 3.9+ Aug 9, 2026 Comprehensions & generators 15 views 0 copies

Python code

10 lines
Python 3.9+
def fib(n):
    a, b = 0, 1
    for _ in range(n):
        yield a
        a, b = b, a + b

if __name__ == "__main__":
    count = 10
    result = list(fib(count))
    print(result)

Output

stdout
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

How it works

The generator uses a two-variable swap pattern where each iteration advances the Fibonacci sequence. Since it's a generator, values are produced lazily one at a time, so memory usage stays constant regardless of how many terms you request. The range(n) loop controls how many numbers to emit before stopping. Calling list() consumes the generator into a concrete list for display. This approach avoids recursion, which would cause exponential time complexity and risk hitting Python's recursion limit.

Common mistakes

  • Forgetting to convert the generator to a list before printing, which only shows the generator object
  • Starting the sequence with (1, 1) instead of (0, 1), which produces a shifted sequence
  • Creating a full list inside the generator, breaking the lazy evaluation and increasing memory usage

Variations

  1. Use `itertools.islice` to take the first N terms from an infinite generator for more flexibility
  2. Return a list comprehension instead for small, fixed-size sequences where memory isn't a concern

Real-world use cases

  • Generating Fibonacci-like lagged sums in financial modeling for exponential growth projections.
  • Building number sequence test data for algorithmic trading backtest simulations.
  • Teaching iterative vs recursive approaches in coding interviews and algorithm analysis.

Sponsored

Run this sample

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

Open editor

More from Comprehensions & generators

Related tutorials and quizzes for this topic.