Python Code Challanges: Lists, how do I make a loop in exercise 2?

I am on exercise 2 in the python code challanges: Lists. (https://www.codecademy.com/courses/learn-python-3/articles/python-code-challenges-lists).

In the exercise, they mention that it is possible to make a loop, but i can´t manage to make one. It doesen´t show how to make the loop in the solution either. Could anyone please respond with how the loop would look like?

Hey there clouds67,

I might be more of a help if I could give you feedback on your code.

But I will do my best to explain my solution to you. My solution is:

def append_sum(lst):
  for i in range(0, len(lst)):
    last = lst[-2] + lst[-1]
    lst.append(last)
  return lst

First, I defined a function that takes one parameter. After that, a loop goes from 0 to the number of elements in the parameter. In this case, 3, so “i” will be: 0, 1, 2.

So first, “i” = 0 will start. I made a new variable that sums up the last two items. I append these to the list. Than “i” = 1 will start, which will do the same, but with the appended item made in “i” = 0—the same principle for “i” = 2.

I hope this was of any help. I am relatively new to coding and helping with coding, so I am open to feedback.

Kind regards,

Benjamin

1 Like

Thank you! I now see the mistake that i made. I had “return lst” inside of the loop so it only printed “[1, 1, 2, 3]”.
This is what my solution was:

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

Also, would you mind explaining if the “0” in “range(0, len(lst)):” is neccesary? Because it seems to work without it aswell.

1 Like

Hey Cloud67,

Glad I could help!

Good question, no the “range(0,” is not necessary. Its just because I was working on loops with lists filled with strings (words) in my course. But in your situation it is not necessary because it already starts at 0.

Thanks for making me aware :slight_smile:

Kind regards,

Benjamin

1 Like

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.