Last modified: Nov 16, 2026
Python Fibonacci Sequence with Examples
The Fibonacci sequence is one of the most famous number patterns in math. It also makes a great practice topic in Python.
Each number in the sequence is the sum of the two before it. The sequence starts with 0 and 1.
So the first terms look like this: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34. This simple rule opens the door to many coding ideas.
In this article, you will learn several ways to generate the sequence in Python. You will see loops, recursion, generators, and more. Each method comes with code and output.
What Is the Fibonacci Sequence?
The rule is easy to state. Start with two seed values, usually 0 and 1.
Then each new term equals the sum of the previous two terms. In math form, that is F(n) = F(n-1) + F(n-2).
This pattern appears in nature, art, and computer science. It shows up in flower petals, spiral shells, and algorithm analysis.
For beginners, it is a perfect playground for loops and functions. It also teaches you about performance and memory.
Method 1: Fibonacci with a For Loop
A simple loop is the easiest way to start. It uses two variables to track the last two numbers.
On each pass, you print the current value and then update both variables. This approach is fast and uses little memory.
# Generate the first n Fibonacci numbers using a loop
def fibonacci_loop(n):
a, b = 0, 1 # seed values
result = []
for _ in range(n):
result.append(a) # store current term
a, b = b, a + b # move to the next pair
return result
print(fibonacci_loop(10))
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Notice the tuple assignment a, b = b, a + b. It swaps values without a temporary variable. This trick keeps the code clean.
This method runs in O(n) time. That is hard to beat for generating a list of terms.
Method 2: Fibonacci with Recursion
Recursion is the textbook definition turned into code. A function calls itself with smaller inputs.
It is elegant to read, but it is slow for large inputs. Each call branches into two more calls.
# Recursive Fibonacci (simple but slow for large n)
def fibonacci_recursive(n):
if n <= 1:
return n # base case: F(0)=0, F(1)=1
return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2)
print(fibonacci_recursive(10))
55
This version recomputes the same values many times. Its time complexity is O(2^n), which grows fast.
Try fibonacci_recursive(35) and you will feel the slowdown. Use it for learning, not for production.
Method 3: Recursion with Memoization
You can fix the slow recursion with caching. Store each result the first time you compute it.
Python gives you a built-in tool for this. The lru_cache decorator from functools remembers past calls.
from functools import lru_cache
# Cached recursion: fast and still readable
@lru_cache(maxsize=None)
def fibonacci_memo(n):
if n <= 1:
return n
return fibonacci_memo(n - 1) + fibonacci_memo(n - 2)
print(fibonacci_memo(50))
12586269025
Now each number is computed only once. The time complexity drops to O(n).
The trade-off is memory. The cache holds every result, so it grows with n.
If you want to explore how decorators pass values around, see this guide on how Python function arguments work.
Method 4: Fibonacci with a Generator
A generator yields one value at a time. It does not build the whole list in memory.
This is ideal when you only need the next number. It is also great for infinite sequences.
# Generator version: yields terms one by one
def fibonacci_gen(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
for num in fibonacci_gen(8):
print(num, end=" ")
0 1 1 2 3 5 8 13
Generators use constant memory. That makes them perfect for streaming data or large ranges.
You can also remove the limit and loop forever. Just wrap the yield in a while True loop.
Method 5: Check If a Number Is Fibonacci
Sometimes you do not want to generate terms. You want to test a single number.
A clever math property helps here. A number n is Fibonacci if and only if one of 5n² + 4 or 5n² - 4 is a perfect square.
import math
# Check if a number belongs to the Fibonacci sequence
def is_fibonacci(n):
def is_square(x):
root = int(math.isqrt(x))
return root * root == x
return is_square(5 * n * n + 4) or is_square(5 * n * n - 4)
print(is_fibonacci(21)) # True
print(is_fibonacci(22)) # False
True
False
This check runs in constant time. No loops or lists are needed.
It pairs well with other number checks. For example, you can compare it with a Python prime number check program to build fun math tools.
Method 6: Fibonacci with Dynamic Programming
Dynamic programming builds answers from smaller ones. For Fibonacci, you can keep a table of results.
This is a good exercise for understanding how caching works under the hood.
# Bottom-up dynamic programming approach
def fibonacci_dp(n):
if n <= 1:
return n
table = [0] * (n + 1)
table[1] = 1
for i in range(2, n + 1):
table[i] = table[i - 1] + table[i - 2]
return table[n]
print(fibonacci_dp(15))
610
This version avoids recursion depth limits. It also gives you every intermediate value if you need them.
You can shrink the table to two variables. That saves memory while keeping the same speed.
Which Method Should You Use?
Use a loop when you need a list of terms. It is fast, simple, and easy to read.
Use a generator when memory matters. It shines for long or infinite sequences.
Use memoized recursion when you want clean code and speed. Avoid plain recursion for large inputs.
Use the math check when you only need to test one number.
These choices also connect to core data structures. Learning how to store results relates to topics like the key differences between Python sets and lists, which affect speed and memory.
Common Mistakes to Avoid
Many beginners start the sequence at 1, 1 instead of 0, 1. Both appear in textbooks, so pick one and stay consistent.
Another common bug is updating variables in the wrong order. Always store the old values before you overwrite them.
Watch out for recursion depth. Python limits deep recursion by default, so very large n will crash.
Also, be careful with large numbers. Python handles big integers well, but output can get long.
If you print floats during math work, you may want to round values to 2 decimal places for cleaner reports.
Conclusion
The Fibonacci sequence is a small idea with big lessons. It teaches loops, recursion, caching, and generators.
Start with the loop version. Then try recursion and memoization to see the speed difference yourself.
Finally, test the generator and the math check. Each method suits a different problem.
Practice with different inputs and print the output. Small experiments build real understanding fast.
With these examples, you can now write clean and efficient Fibonacci code in Python.