Using a loop on a question in the 1st Python code challenge

On this exercise:

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 answer was:

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

which was correct but it also mentions at the bottom a loop could be used to solve as well.

You could also use a loop to solve this instead of repeating the lines.

How would you use a loop to solve this?

The key detail is three times, so a loop over a range of 3,

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

Ah, I can see range coming in very useful for things like this. Thanks.

1 Like