Python Code Challenges: Lists

2. Append Sum:

Why doesn’t this code do the job?

#Write your function here
def append_sum(lst):
    for i in range(len(lst)):
      lst.append(lst[-1] + lst[-2])
  return lst
#Uncomment the line below when your function is done
print(append_sum([1, 1, 2])) # prints [1, 1, 2, 3, 5, 8]
print(append_sum([2, 5])) # prints [2, 5, 7, 12]         (without 19)

because you loop over the length of the list:

for i in range(len(lst)):

so the amount of times the loop runs depends on the length of the list

you should simply loop 3 times (regardless of the list length)

1 Like