-3

Why I am getting an error:

list assignment out of range.

def febonaci(n):
    f=list();
    f[0]=0
    f[1]=1
    for i in range(2,n):
        f[i]=f[i-1]+f[i-2]
    return f[i]

n=int(input('Enter an number: '))
febonaci(n)
jps
  • 20,041
  • 15
  • 75
  • 79
  • 2
    Does this answer your question? [Why does this iterative list-growing code give IndexError: list assignment index out of range?](https://stackoverflow.com/questions/5653533/why-does-this-iterative-list-growing-code-give-indexerror-list-assignment-index) – Tomerikoo Oct 01 '20 at 14:36

2 Answers2

0

You are getting a error because of the lines f[0]=0 and f[1]=1. You can only assign numbers like this if they already exist inside the list. But since you list is empty if throws an error. See this example

tmp = list()   # Create an empty list
tmp.append(0)  # Add items to list
tmp.append(1)
print(tmp[0])  # Print
print(tmp[1])

tmp[0] = 10    # Can now overwrite items using list_name[some_num] = ...
print(tmp[0])  # Print

If you want to create a Fibonacci sequence, you will have to use a recursive function like below.

def Fibonacci(n):
    if n<=0:
        return # Cannot 
    elif n==1:
        return 0
    elif n==2:
        return 1
    else:
        return Fibonacci(n-1)+Fibonacci(n-2)
 
print(Fibonacci(9))
John Salzman
  • 500
  • 5
  • 14
0

You also can do it without recursion, iteratively:

def fibonacci(n):
    if n <= 0:
        return  
    elif n == 1 or n == 2:
        return 1

    f1 = 1
    f2 = 1
    f3 = 2
    for _ in range(n-3):
        f1 = f2
        f2 = f3
        f3 = f1 + f2
    return f3
Fedor Soldatkin
  • 1,133
  • 8
  • 23