How to Generate Fibonacci Sequence in Python
Generate the first n Fibonacci numbers as a list using a simple iterative loop.
Python code
13 linesdef fibonacci(n):
"""Generate the first n terms of the Fibonacci sequence."""
if n <= 0:
return []
seq = [0, 1]
while len(seq) < n:
seq.append(seq[-1] + seq[-2])
return seq[:n]
if __name__ == "__main__":
n = 10
result = fibonacci(n)
print(result)
Output
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
How it works
The function initializes the list with the first two Fibonacci numbers, 0 and 1. It then repeatedly appends the sum of the last two elements until the list reaches the desired length. Finally, it returns the slice seq[:n] to handle the case where n is 1, ensuring only the first term is returned. This iterative approach is efficient with O(n) time and O(n) space, avoiding the exponential overhead of naive recursion.
Common mistakes
- Not handling n <= 0, which can cause a loop that never terminates or an error.
- Returning the full list instead of slicing `seq[:n]` when n is 1, which would include an extra 1.
- Using recursion without memoization, which leads to exponential time for larger n.
Variations
- Use a generator to yield Fibonacci numbers lazily: `def fib(): a, b = 0, 1; while True: yield a; a, b = b, a + b`.
- Use a list comprehension with `itertools.islice` to get the first n terms from the generator.
Real-world use cases
- Generating test data for dynamic programming practice problems.
- Calculating sequence lengths in nature-inspired algorithms, like Fibonacci search.
- Building sample arrays for benchmarking time-complexity experiments.
Sponsored
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.