TechBeamersTechBeamers
  • Viral Tips 🔥
  • Free CoursesTOP
  • TutorialsNEW
    • Python Tutorial
    • Python Examples
    • C Programming
    • Java Programming
    • MySQL Tutorial
    • Selenium Tutorial
    • Selenium Python
    • Playwright Python
    • Software Testing Tutorial
    • Agile Concepts
    • Linux Concepts
    • HowTo Guides
    • Android Topics
    • AngularJS Guides
    • Learn Automation
    • Technology Guides
  • Top Interviews & Quizzes
    • SQL Interview Questions
    • Testing Interview Questions
    • Python Interview Questions
    • Selenium Interview Questions
    • C Sharp Interview Questions
    • Java Interview Questions
    • Web Development Questions
    • PHP Interview Questions
    • Python Quizzes
    • Java Quizzes
    • Selenium Quizzes
    • Testing Quizzes
    • HTML CSS Quiz
    • Shell Script Quizzes
  • ToolsHOT
    • Python Online Compiler
    • Python Code Checker
    • C Online Compiler
    • Review Best IDEs
    • Random Letter Gen
    • Random Num Gen
TechBeamersTechBeamers
Search
  • Viral Tips 🔥
  • Free CoursesTOP
  • TutorialsNEW
    • Python Tutorial
    • Python Examples
    • C Programming
    • Java Programming
    • MySQL Tutorial
    • Selenium Tutorial
    • Selenium Python
    • Playwright Python
    • Software Testing Tutorial
    • Agile Concepts
    • Linux Concepts
    • HowTo Guides
    • Android Topics
    • AngularJS Guides
    • Learn Automation
    • Technology Guides
  • Top Interviews & Quizzes
    • SQL Interview Questions
    • Testing Interview Questions
    • Python Interview Questions
    • Selenium Interview Questions
    • C Sharp Interview Questions
    • Java Interview Questions
    • Web Development Questions
    • PHP Interview Questions
    • Python Quizzes
    • Java Quizzes
    • Selenium Quizzes
    • Testing Quizzes
    • HTML CSS Quiz
    • Shell Script Quizzes
  • ToolsHOT
    • Python Online Compiler
    • Python Code Checker
    • C Online Compiler
    • Review Best IDEs
    • Random Letter Gen
    • Random Num Gen
Follow US
© TechBeamers. All Rights Reserved.
Python Examples

Python Program: 6 Ways to Generate Fibonacci Sequence

Last updated: Apr 14, 2025 1:11 am
Meenakshi Agarwal
By
Meenakshi Agarwal
Meenakshi Agarwal Avatar
ByMeenakshi Agarwal
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large...
Follow:
No Comments
2 months ago
Share
9 Min Read
SHARE

In this short tutorial, you’ll learn multiple ways to generate a Fibonacci sequence in Python and display it using the print() method. But, let’s first quickly understand the background and importance of Fibonacci in mathematics.

Contents
What is Fibonacci series and why is it important?Different ways to generate Fibonacci sequenceMethod 1. Using while LoopMethod 2. Using recursionMethod 3. Using memoizationMethod 4. Using generator functionMethod 5. Using matrix exponentiationMethod 6. Using closed-form formula
Python program to generate a Fibonacci sequence

What is Fibonacci series and why is it important?

The concept of Fibonacci first came into existence in 1202 from a book by an Italian mathematician. The title of the book was “Liber Abaci.” However, similar sequences existed in Indian mathematics before his work. Fibonacci starts with 0 and 1 and then grows by adding every two consecutive numbers. For example, here is a shorter version of the series.

# Standard Fibonacci sequence
# 
0, 1, 1, 2, 3, 5, 8...

The Fibonacci sequence is important in mathematics because it has many interesting properties and appears in many unexpected places in nature and art. For example, the Fibonacci sequence can be used to:

Modeling the growth of populations
Describing spiral patterns in nature
Creating aesthetically pleasing designs
Developing efficient algorithms for computer science problems

Different ways to generate Fibonacci sequence

There are several ways to generate a Fibonacci sequence in Python. We’ll try to cover most of those methods. Firstly, let’s start with the basic one.

Method 1. Using while Loop

You can use a loop, such as a for or while loop, to generate a Fibonacci sequence by iteratively adding the last two numbers in the sequence to produce the next number. Here’s a sample program using a while loop:

For writing this demo code, you should be familiar with the Python basics. To prepare yourself, the following topics could help you:

  • Python if else
  • Python while loop

We’ll use both of the above constructs to form the Fibonacci sequence in the sample given below. This series is a list of integer numbers as shown here.

The above sequence starts with the two pre-defined numbers 0 and 1. The remaining other values get generated by adding the preceding two digits appearing in the list.

It means if you wish to know the value at the index X, then it would be the sum of values at the (X-1) and (X-2) positions.

In the below program, we are using two numbers X and Y to store the values for the first two elements (0 and 1) of the Fibonacci sequence.

After that, there is a while loop to generate the next elements of the list. It is doing the sum of two preceding items to produce the new one.

There is a swapping operation in the next line to continue the while loop until the last element of the sequence gets printed.

# Python code to generate Fibonacci seq using while loop

# The length of our Fibonacci sequence
length = 10

# The first two values
x = 0
y = 1
iteration = 0

# Condition to check if the length has a valid input
if length <= 0:
   print("Please provide a number greater than zero")
elif length == 1:
   print("This Fibonacci sequence has {} element".format(length), ":")
   print(x)
else:
   print("This Fibonacci sequence has {} elements".format(length), ":")
   while iteration < length:
       print(x, end=', ')
       z = x + y
       # Modify values
       x = y
       y = z
       iteration += 1

There could be three possible outputs of the above code.

The length of the sequence is 0 or less than zero.

Please provide a number greater than zero

The sequence contains a single element.

This Fibonacci sequence has 1 element :
0

The sequence contains multiple elements.

This Fibonacci sequence has 10 elements :
0, 1, 1, 2, 3, 5, 8, 13, 21, 34,

You can further play with the program by supplying different values for the length variable.

Method 2. Using recursion

You can also generate a Fibonacci sequence using a recursive function. Here’s an example:

def fibo_recursive(n):
    if n <= 0:
        return []
    elif n == 1:
        return [0]
    elif n == 2:
        return [0, 1]
    else:
        seq = fibo_recursive(n - 1)
        seq.append(seq[-1] + seq[-2])
        return seq

n = 10  # Change 'n' to the desired size of the seq
result = fibo_recursive(n)
print(result)

Method 3. Using memoization

You can optimize the recursive approach by using memoization to store previously calculated Fibonacci numbers to avoid redundant calculations. This can be more efficient for larger values of n.

def fib_memo(n, memo={}):
    if n in memo:
        return memo[n]
    if n <= 0:
        return []
    elif n == 1:
        return [0]
    elif n == 2:
        return [0, 1]
    else:
        seq = fib_memo(n - 1, memo)
        seq.append(seq[-1] + seq[-2])
        memo[n] = seq
        return seq

n = 10  # Change 'n' to the desired size of the seq
result = fib_memo(n)
print(result)

Memoization is an advanced version of recursion optimizing it for speed. It caches the expensive function calls and uses the same instead of recomputing them.

Method 4. Using generator function

You can create a generator function to yield Fibonacci numbers one at a time, which is memory-efficient and can be used in a for loop or with the next() function to generate values on the fly.

def gen_fibo(n):
    a, b = 0, 1
    for _ in range(n):
        yield a
        a, b = b, a + b

n = 10  # Change 'n' to the desired size of the seq
result = list(gen_fibo(n))
print(result)

Method 5. Using matrix exponentiation

It is a technique that can be used to calculate Fibonacci numbers more efficiently for large values of n. It involves raising a specific matrix to the power of n. Here’s a simplified example of how you can do this:

import numpy as np

def matrix_fibo(n):
    if n == 0:
        return 0
    F = np.array([[1, 1], [1, 0]], dtype=object)
    result = np.linalg.matrix_power(F, n - 1)
    return result[0, 0]

size = 10  # Length of Fibonacci series to print

fibonacci_series = [matrix_fibo(i) for i in range(size)]
print(fibonacci_series)

Method 6. Using closed-form formula

This method doesn’t require a loop or function, instead, use the following formula.

F(n) = (phi^n - (-phi)^(-n)) / sqrt(5)

In this, phi is the golden ratio, a mathematical constant equal to 1.61803. You can use this formula in your Python code to generate a Fibonacci sequence.

Here’s an example of how you can use this formula:

import math

def fibo_formula(n):
    phi = (1 + math.sqrt(5)) / 2
    return round((math.pow(phi, n) - math.pow(-phi, -n)) / math.sqrt(5))

size = 10  # Length of Fibonacci series to print

fibonacci_series = [fibo_formula(i) for i in range(size)]
print(fibonacci_series)

Please note that the last two methods improve efficiency and precision in the case of large Fibonacci numbers. However, the matrix exponentiation method may need extra libraries like NumPy for the calculation.

We hope these multiple ways to generate the Fibonacci sequence will help you write better Python programs. You can choose which method works best for your use case.

Lastly, our site needs your support to remain free. Share this post on social media (Linkedin/Twitter) if you gained some knowledge from this tutorial.

Enjoy Coding,
TechBeamers

Related

Share This Article
Flipboard Copy Link
Subscribe
Notify of
guest

guest

0 Comments
Newest
Oldest
Inline Feedbacks
View all comments

List of Topics

Stay Connected

FacebookLike
XFollow
YoutubeSubscribe
LinkedInFollow

Subscribe to Blog via Email

Enter your email address to subscribe to latest knowledge sharing updates.

Join 1,011 other subscribers

Continue Reading

  • Python Program: Generate Fibonacci using RecursionOct 31
  • Python Program: Convert Lists into a DictionaryNov 1
  • Python Program: Insert Key-Value Pair in a DictionaryNov 13
  • Python Program: When to Prefer Yield Over ReturnDec 7
  • Python Program: Learn to Build an IRC BotApr 3
  • Python Program to Find Sum of Two NumbersOct 9
  • Python Program: Swap Two Numbers Without a TempOct 10
  • Python Program: Generate Random IntegerOct 17
  • Python Program: Check List Contains Another List ItemsOct 21
  • Python Program: How to Sort Lists AlphabeticallyFeb 11
View all →

RELATED TUTORIALS

Search keys by values in a Python dictionary

Python Program: Search Keys by Value in a Dictionary

By Meenakshi Agarwal
11 months ago
Python Sort Using Lambda With Examples

Python Program: How to Sort with Lambda

By Soumya Agarwal
11 months ago
Python Sort a List in Descending Order With Examples

Python Program: Sort List in Descending Order

By Soumya Agarwal
11 months ago
Python character frequency in string

Python Program: Python Character Frequency

By Meenakshi Agarwal
9 months ago
© TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
wpDiscuz