In this tutorial, you will learn to write a Python Program To Print Fibonacci Series Using List.
The Fibonacci series is a sequence of numbers in which each number is the sum of the two preceding numbers.
The first two numbers in the series are 0 and 1, and the rest of the series is generated by adding the previous two numbers.
Therefore, the series starts like this:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, …
To understand this program you should have an understanding of the following topics:
- Python Recursion
- Python Lists
- For Loop
Python Program To Print Fibonacci Series Using List
n = int(input("Enter the number of terms: "))
# create a list to store the series
fibonacci = [0, 1]
# extend the list with the first n-2 terms of the series
for i in range(2, n):
fibonacci.append(fibonacci[i-1] + fibonacci[i-2])
# print the entire series
for i in range(n):
print(fibonacci[i], end=' ')
Output
Enter the number of terms: 15
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
In this code, we start by getting the value of n from the user.
This value determines how many terms of the Fibonacci series we want to print.
We then create a list called fibonacci and initialize it with the first two terms of the series as fibonacci = [0, 1].
We then use a for loop to extend the fibonacci list with the first n-2 terms of the series.
Inside the loop, we append the next term of the series to the end of the list by adding the previous two terms.
Finally, we use another for loop to print out the entire series up to the nth term.
We simply print out the values of the ith element of the fibonacci list inside the loop.
By using a list to store the series, we avoid the redundant computation that can occur with the recursive method.
And we also avoid the need to update multiple variables in a loop as in the iterative method.
Discover more from Python Mania
Subscribe to get the latest posts sent to your email.