Free lab Real Python 3. Zero installs. Your code stays in this browser. Open the playground

Fibonacci Sequence

Medium · 50 XP

Print the first 10 Fibonacci numbers (starting 0, 1) on one line separated by spaces.

Target output
0 1 1 2 3 5 8 13 21 34
Blank · autosaved
PYfibonacci.py
Run your code to check it…
Guide

How to approach Fibonacci Sequence

Each Fibonacci number is the sum of the two before it, so you only ever need to remember two values. Start with a, b = 0, 1; on each step, record a, then move both forward.

The move is a, b = b, a + b. Python evaluates the whole right-hand side before assigning anything, so the old a is still available when a + b is computed. Collect the numbers in a list and print them with " ".join(map(str, fibs)), because join only accepts strings.

Worked through on this data

  1. Start a = 0, b = 1. Record 0, then a, b = 1, 1.
  2. Record 1, then 1, 2. Record 1, then 2, 3. Record 2, then 3, 5. Record 3, then 5, 8.
  3. Continue for ten records in total: 0 1 1 2 3 5 8 13 21 34.

Common mistakes

  • Two separate lines, a = b then b = a + b, overwrite a too early and produce 0 1 2 4 8 16, doubling instead of adding.
  • Printing the list directly shows brackets and commas: [0, 1, 1, ...].
  • Off-by-one: starting at 1, 1 or looping 11 times gives the wrong ten numbers.

Time and space

The loop is O(n) time and the list is O(n) space. The naive recursive definition fib(n - 1) + fib(n - 2) is O(2^n), because it recomputes the same values again and again.

Where this shows up

Carrying a small amount of state forward through a loop, rather than recomputing from scratch, is the core of running totals, moving averages and dynamic programming.

Take it further

Turn it into a generator function with yield, then print the first Fibonacci number with more than 100 digits.

Your next ten minutes

Write Python that does something useful.

Start free. No install, no card, no passive video marathon.

Start learning free → Explore the path