The Fibonacci Series in Python

Rate this post

The Fibonacci series was discovered by the Italian mathematician Leonardo Fibonacci in 1202 and even earlier by Indian mathematicians. The series appears in unexpected areas such as economics, mathematics, art, and nature.

Algorithm Sketch

In the following, we give a simple algorithm to calculate the Fibonacci numbers.

The series starts with the Fibonacci numbers zero and one. The algorithm calculates the next element of the series as the sum of both last elements. For this, the algorithm has to keep track only of the last two elements in the series. Thus, we maintain two variables a and b, being the second last and last element in the series, respectively.
This computation repeats for 10 iterations using a standard for loop:

# Algorithm to Computer
# Fibonacci Series

a, b = 0, 1
for i in range(10):
    a, b = b, a+b

The output are the first 10 Fibonacci numbers:


For clarity of the code, we used the language feature of multiple assignments in the first and the last line.

This feature works as follows.

  • On the left-hand side of the assignment, there is any sequence of variables such as a list or a tuple.
  • On the right-hand side of the assignment, we specify the values to be assigned to these variables.

Both sequences on the left and on the right must have the same length. Otherwise, the Python interpreter will throw an error.

Note that all expressions on the right-hand side are first evaluated before they are assigned. This is an important property for our algorithm. Without this property, the last line would be wrong as expression a+b would consider the wrong value for a.

How to Store First n Fibonacci Numbers in a List?

Recap, the Fibonacci series is the series of numbers that arises when repeatedly summing up the last two numbers starting from 0 and 1. Here’s an algorithm that stores the first n Fibonacci numbers in a list and returns the list:

def fibo(n):
    result = []
    a, b = 0, 1
    while a < n:
        a, b = b, a+b
    return result

fib100 = fibo(100)
print(fib100[-1]== fib100[-2]+fib100[-3])
# True

The fibo function in the code calculates all Fibonacci numbers up to the function argument n.

Again, we use the concise method of multiple assignment to store the value of b in the variable a and to calculate the new value of b as the sum of both. We maintain the whole sequence in the list variable result by appending the sequence value a to the end of the list.

The code calculates the Fibonacci sequence up to 100 and stores the whole list in the variable fib100. But to understand the code, you do not have to calculate the whole sequence. The print statement only compares whether the last element is equal to the sum of the second and third last element in the sequence. This is true by definition of the Fibonacci series.

A Simple Python Puzzle About the Fibonacci Series

Can you solve the following puzzle about the Fibonacci algorithm?

Are you a master coder?
Test your skills now!

Watch the Related Video Fibonacci One-Liner

I love one-liners. So much so that I’ve written a book Python One-Liners about how to compress Python code into a single line of Python code. As it turns out, you can express the Fibonacci algorithm in a single line of code. Watch the video to see how!

Fibonacci in One Line Python

The one-liner code to compute the Fibonacci numbers in a single line is the following:

# Dependencies
from functools import reduce

# The Data
n = 10

# The One-Liner
fibs = reduce(lambda x, _: x + [x[-2] + x[-1]], [0] * (n-2), [0, 1])

# The Result

You can read a detailed explanation in my full tutorial.

Related Tutorial: The Fibonacci Algorithm in a Single Line of Python Code

Math-Based Explainer Video Fibonacci

The Fibonacci Sequence and the Golden Ratio

Now, that you’ve learned all about the Fibonacci algorithm, I’m sure you want to test your skills!

An Advanced Python Puzzle About Fibonacci

The following puzzle is an advanced-level Fibonacci puzzle. Can you solve it?

Are you a master coder?
Test your skills now!

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

Leave a Comment