I'm still something of a beginner with Python and I was trying to optimise a function to generate the Fibonacci sequence to a specified number of values. This is the code I have written:
def attempt2(length):
listy=[]
for i in range(0,length+1):
if i == 0:
listy.append(1)
elif i == 1:
listy.append(1)
else:
listy.append(listy[i]+listy[i-1])
return listy
Whilst keeping this structure I have found no way to overcome the 'list index out of range' error. I think because the listy[i-1] would be out of range when i = 0, but if the function progresses through the loop linearly then the else statement should only take effect when i = 2. Can anyone see what I'm doing wrong?
Thanks!
So, to find out the source of your issue, we need to take a step back to see what your loop is doing.
Initially, your for-loop is counting from 0 to whatever the length is, let's see what the values for i will look like:
0 1 2 ...
so starting from 2, since the behavior of 0,1 is defined:
listy.append(listy[2]+listy[1])
Remember that listy has 2 items now, which are zero indexed, in other words the items are 1 and 0, hence the item listy[2] doesn't exist.
Thus, your code should be
listy.append(listy[i-2]+listy[i-1])