Help with returning a loop within a function


I am new to Python and am currently taking Codecademy’s Python 3 course. I am having difficulty completing one code challenge that requires returning a loop within a function.

The challenge requires defining a function that adds the last two elements of the list together, and then appends that summation to the end of the same list. I was able to do this:

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

However, the challenge also requires the function to return the appended list three times, using a loop function. Here is what I have tried so far, however I continue to receive a syntax error:

lst.append(lst[-1] + lst[-2]) for x in range(4)
return lst

Any help is greatly appreciated.


1 Like

hi i want to help you but can you put code like this by pressing </>

What you have already appends the sum of the last 2 numbers to the list of numbers.

def append_sum(lst): lst.append(lst[-1] + lst[-2]) #1 lst.append(lst[-1] + lst[-2]) #2 lst.append(lst[-1] + lst[-2]) #3 return lst numbers = [1, 2, 3, 4] print(numbers) append_sum(numbers) print(numbers)

The same code that’s in the codeByte above could be done with a for-loop.

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

notice that the value of x would be 0, then 1, then 2 for the loop.
So, if you want something to repeat 3 times, you could do range(3) for the for-loop.

I sincerely appreciate the help!