# How to iterate adding values and appending lists

Hello I’m wondering if anyone can help me solve a problem. I’m currently doing the list optional challenges and one of the questions is to add two values at the end of the list together, then append the sum to the end of the list. This must be done three times. I’ve completed this challenge but I’m unhappy with the way I’ve done it since I thought of a better way but I’m not sure how to do it. My idea is to use a for loop to iterate appending onto the list instead of writing the same line out three times.

def append_sum(lst): lst.append(lst[-1] + lst [-2]) lst.append(lst[-1] + lst [-2]) lst.append(lst[-1] + lst [-2]) return lst print(append_sum([1, 1, 2]))

I’ve tried doing

def append_sum(lst): for i in lst: lst.append(lst[-1] + lst [-2]) return lst

But the console gave me a blank screen.

With your second code example, you’ve created an infinite loop. Because you’re appending items to the end of the list you’re iterating through, the list is getting longer every iteration. That means the loop will never get to the end of the list, and will therefore keep iterating.

If you wanted to use a loop, you could loop through a range instead of the list:

``````for _ in range(0,3):
#code
``````
1 Like