Robin Duong
Robin Duong

Reputation: 71

IndexError: List Index Out of Range When Appending to a List in Python

I am trying to generate the Fibonacci value of a number efficiently, but my code returns this error:

"Traceback (most recent call last):
  File "fibonacci_number.py", line 22, in <module>
    print(fibonacci_number(input_n))
  File "fibonacci_number.py", line 16, in fibonacci_number
    next_num = fib_list[n-2] + fib_list[n-1]
IndexError: list index out of range"

Here is the full code:

def fibonacci_number(n):
assert 0 <= n <= 45
fib_list = [0, 1]
for i in range(2, n):
    next_num = fib_list[n-2] + fib_list[n-1]
    fib_list.append(next_num)
return fib_list[n]

if __name__ == '__main__':
    input_n = int(input())
    print(fibonacci_number(input_n))

I don't want to call fibonacci_number() recursively, as it will make me recalculate fib_list[n-2] and fib_list[n-1] over and over, which takes up time.

I found other people with similar issues, but using ".append()" seemed to resolve their issue of adding something new to a Python list.

Some things I've tried:

  1. fib_list = fib_list.append(next_num)
  2. fib_list.append(fib_list[n-2] + fib_list[n-1])
  3. declaring next_num separately and setting it equal to 0 before later updating its value

Upvotes: 1

Views: 116

Answers (1)

davetherock
davetherock

Reputation: 365

The error is in this line:

next_num = fib_list[n-2] + fib_list[n-1]

You are always setting next_num using "n", which would mean you're calculating the final number in your list. You want to replace this line with

next_num = fib_list[i-2] + fib_list[i-1]

You should also change to

return fib_list[n-1]

BTW, if you want to calculate the n-th fibonacci number SUPER efficiently, I would recommend using another method from this article.

Upvotes: 1

Related Questions