How to Generate Fibonacci Sequence in Python

Generate the first n Fibonacci numbers as a list using a simple iterative loop.

Easy Python 3.9+ Aug 9, 2026 Algorithms & data structures 13 views 0 copies

Python code

13 lines
Python 3.9+
def 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

stdout
[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

  1. Use a generator to yield Fibonacci numbers lazily: `def fib(): a, b = 0, 1; while True: yield a; a, b = b, a + b`.
  2. 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

Run this sample

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

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.