Https://www.codecademy.com/paths/computer-science/tracks/cspath-flow-data-iteration/modules/dspath-lists/articles/python-code-challenges-lists

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]

I’m not sure why, but I am having trouble with this. Essentially, I can’t wrap my head around how to access the last two values inside the list, index -1 and -2, and append it to the list while adding them together. I believe it is something simple…but brain no work

def append_sum(lst):
  add = lst[-2:]

  lst = lst.append(add[0] + add[1])
  print[lst]
  
#Uncomment the line below when your function is done
print(append_sum([1, 1, 2]))

Hi there.

I presume that this is not working because you’re getting None back from the function?

It would be easy to assume that this is because your function lacks a return statement - which it does, and the default return type for Python if you omit one is None - but this is not actually the problem.

The issue is with this line:

    lst = lst.append(add[0] + add[1])

You’ve correctly identified that we should use the list type’s built-in method append to add the sum of the last two items to the list… however, you’re reassigning the value of lst to the return value of the append method… which is None.

You can verify this with the following code:

>>> test = [1,2,3,4]
>>> print(test.append(5))
None
>>>

Since your code is overwriting the value of lst with None, this is the output you’ll see on the console when you subsequently call print on the final line of your function.

The call to print at the end, print(append_sum([1,1,2])) will also print None… for the reasons relating to your return value I explained above. :slight_smile:

Hope that helps.

2 Likes
def append_sum(lst):
  add = lst[-2:]

  add = lst.append(add[0] + add[1])
  add = lst[-2:]

  add = lst.append(add[0] + add[1])
  add = lst[-2:]

  add = lst.append(add[0] + add[1])
  return lst
  print[lst]
  
#Uncomment the line below when your function is done
print(append_sum([1, 1, 2]))

Thanks, that helped me figure out what I needed to change!

1 Like