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.
Python code
10 linesdef 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
[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
- Use `itertools.islice` to take the first N terms from an infinite generator for more flexibility
- 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
More from Comprehensions & generators
- Batch Rows in Chunks with a Generator in Python easy
- Build a Generator Pipeline in Python: Filter Then Map medium
- Build a lazy generator to read file lines in Python easy
- Chunk an Iterable into Batches with a Generator in Python easy
- Convert Data in Python with Comprehensions and Generators easy
- Count Data in Python with Comprehensions and Generators easy
Keep learning
Related tutorials and quizzes for this topic.