Python Fibonacci Sequence Generator

Run and understand the Fibonacci sequence in Python. This interactive code example shows iterative and recursive approaches to generating Fibonacci numbers.

Try Python Fibonacci Sequence Generator Code

How it Works

The Fibonacci sequence is a series of numbers where a number is the addition of the last two numbers, starting with 0 and 1.

It is a classic computer science problem, often used to teach recursion, dynamic programming, and loop iteration.

In Python, we can generate the Fibonacci sequence efficiently using a loop (iterative approach) which avoids the stack overflow risks of deep recursion.

Source Code

This script generates the first N numbers of the Fibonacci sequence using a highly efficient while loop.

fibonacci.py
Try in Editor
def generate_fibonacci(n):
    fib_list = []
    a, b = 0, 1
    
    while len(fib_list) < n:
        fib_list.append(a)
        a, b = b, a + b
        
    return fib_list

# Generate the first 10 Fibonacci numbers
terms = 10
result = generate_fibonacci(terms)
print(f"First {terms} Fibonacci numbers:")
print(result)
Terminal Output
First 10 Fibonacci numbers:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Real-world Applications

  • Algorithm analysis and optimization testing
  • Modeling biological growth patterns mathematically
  • Technical interview preparation

Frequently Asked Questions

Is the recursive Fibonacci approach better?

In most production code cases, no. The simple recursive approach runs in O(2^n) time which is incredibly slow. The iterative loop runs in O(n) making it far superior unless memoization is used.

More Examples