Python Code Challanges: Lists

Hi!

I am taking Learn Python 3 course. In the second question of Python Code Challenges: Lists, I got an error message saying “list index out of range” even though my result is same as the one provided by Codecademy.

Here is the question:


And here is my solution:

def append_sum(lst): i=1 while i<4: lst.append(lst[i] + lst[i+1]) i += 1 return lst print(append_sum([1, 1, 2]))

If you help me find what is wrong with my code, I will appreciate. Thanks in advance!

Your code works if the list has 3 elements.
But if the list has 2 elements, then you get an index out of range error.
e.g. append_sum([1, 1]) will give an error.

Similarly, if the list has 4 or more elements, then your code will give incorrect answer. e,g,

append_sum([1, 1, 2, 3])   
# Incorrect output: [1, 1, 2, 3, 3, 5, 6]
# Expected output: [1, 1, 2, 3, 5, 8, 13]

Since you have initialized i = 1, your code only works for lists with three elements. If you want to use positive indexes, then you will have to use the length of the list to pick an appropriate value to initialize i. You will also have to modify the while condition. Instead of all that, using negative indexes to target the last two elements (as shown in the hints in your screenshot) is much simpler.

1 Like