Printing the fibonacci series upto ten elements in a python list

209 views Asked by At

So, as a beginner in Python, I have been trying to solve practice problems in loops and if-else statements to get a good grip on the basics of program flow and control statements. I was working on this problem where I have to print the Fibonacci series up to ten elements like this:

Output: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 Link: https://pynative.com/python-if-else-and-for-loop-exercise-with-solutions/#h-exercise-12-display-fibonacci-series-up-to-10-terms.

And I have managed to do this but there are also a bunch of random values printed after the number 55 and I have no idea why this happened. Please guide me on how to remove these values. Also, tell me how do you make a python list with placeholder values? I have used "None" keyword in my list to do this but I feel like there has to be a better way to do this:

list1=[0, 1, None, None, None, None, None, None, None, None]

for i in range(2, 11):

    list1[i]=list1[i-1]+list1[i-2]

    list1.append(list1[i])

print(list1)

OUTPUT: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 1, 2, 3, 5, 8, 13, 21, 34]. Why are these extra values after 34 being printed in the list? Please explain. I expect the output of this to be: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34].

5

There are 5 answers

0
JustLearning On

Instead of preallocating None's in a list, you can append new values:

N = 10 # for a total sequence of length 10.
fib = [1, 1]
for i in range(2, N):
    fib.append(fib[i - 1] + fib[i - 2])
3
Khaled DELLAL On

You have to use only append inside the loop

list1=[0, 1]
for i in range(2, 11):

    list1.append(list1[i-1]+list1[i-2])

print(list1)

Output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

1
Himanshu Sharma On
def fibonacci(n):
    # defining the first two fibonacci numbers
    fibonacci_sequence = [0, 1]
    
    
    while len(fibonacci_sequence) < n:
        fibonacci_sequence.append(fibonacci_sequence[-1] + fibonacci_sequence[-2])
    
    return fibonacci_sequence


fibonacci_numbers = fibonacci(10)


for index, fibonacci_number in enumerate(fibonacci_numbers):
    print(f"fibonacci_{index+1} = {fibonacci_number}")
1
Rajath R K On
num = 5
factorial = 1
if num < 0:
    print("Factorial does not exist for negative numbers")
elif num == 0:
    print("The factorial of 0 is 1")
else:
    # run loop 5 times
    for i in range(1, num + 1):
        # multiply factorial by current number
        factorial = factorial * i
    print("The factorial of", num, "is", factorial)
 
0
user16171413 On

Nice solutions already suggested. A more pythonic approach would be:

list1 = []                    # Start your list empty
a, b = 0, 1                   # Your initial values
for i in range(11):           # number of iterations
    list1.append(a)           # append to the list
    a, b = b, a+b             # find other values
print(list1)                  # print list after completing iteration

Output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]