Python Code Challenges: Lists

Challenge

Hi,

I have finished the first challenge but wondered if there is a way of just looping my code rather than typing it out 3 times? I checked out for and while loops online but couldn’t see how to make it work here?
Any help would be appreciated

Question - Write a function named append_sum that has one parameter — a list named named lst .

The function should add the last two elements of lst together and append the result to lst . It should do this process three times and then return lst .

For example, if lst started as [1, 1, 2] , the final result should be [1, 1, 2, 3, 5, 8] .

My code
#Write your function here

def append_sum(lst):
sum0 = (lst[-1] + lst[-2])
lst.append(sum0)
sum0 = (lst[-1] + lst[-2])
lst.append(sum0)
sum0 = (lst[-1] + lst[-2])
lst.append(sum0)
return lst

#Uncomment the line below when your function is done
print(append_sum([1, 1, 2]))

:slight_smile:

def append_sum(lst):
for x in range(1,4):
sum0 = (lst[-1] + lst[-2])
lst.append(sum0)
return lst
print(append_sum([1, 1, 2]))

1 Like