Python Code Challenges: Lists [2. append sum]

I am doing the python code challenges for control flow, and i came to a part of the challenges that relates to lists…th exercise says you can use a loop or 3 lines… i tried to do it with a loop and when i click on “RUN”, i get the expected result…but when i click on “Check answer” i get something that doesn’t make sense to me:

#Write your function here
def append_sum(lst):
  for last2 in lst:
    lst.append(lst[-1] + lst[-2])
    if len(lst) == 6:
      return lst

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

The result is:

[1, 1, 2, 3, 5, 8]

which as per the instructions…is the expected result…but? what’s going on here then?

you assume the list passed as argument always has a length of three, this is not true. The function should be able to handle the list of any length

as you can see at the bottom error message, calling append_sum() with [2, 5] as argument gives a list with 6 values, this should 5 values (3 added values)

1 Like

ahhhh!..duh!..thanks for pointing what now seems obvious…

so this did the trick then

def append_sum(lst):
  counter = 0
  for last2 in lst:
    lst.append(lst[-1] + lst[-2])
    counter += 1
    if counter == 3:
      return lst