Python Code Challenges: Lists

I’ve been attempting to complete these code challenges after complete the LIST part of the python course. I am having a very hard time understanding what is being asked of me in these challenges. https://www.codecademy.com/courses/learn-python-3/articles/python-code-challenges-lists

The first challenge :

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] .

Hello, @hamidpoole, and welcome to the forums.

I’m not sure where exactly you’re getting stuck. To solve this first challenge, consider how you can access the last element of a list, and also the second to last element. You’ll want to add the values of those elements together, and then using something like append() add the resulting value to the end of the list. Hopefully this will help you to get started.

Try to explain better where you get stuck or what you do not understand how to do… anyway for access to the last 2 value of the list you should index them and then append everything to the list… and repeat this 3 time :slight_smile: .

for instance:

def append_items(list):
    sum0 = (list[-1] + list[-2])
    list.append(sum0)

now use the same principle on your piece of code within different name off course :slight_smile:

Hello, I keep getting “NONE” printed out, do you have any idea why ? Everything seems fine to me :

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


print(append_sum([1, 1, 2]))

I tried a bunch of different versions but I get an error instead :

def append_sum(lst):
    lst2 = (lst[-2] + lst[-1])
    return lst + lst2


print(append_sum([1, 1, 2]))

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

print(append_sum([1, 1, 2]))

You are returning the return value of list.append(lst2), which is None!

For the other versions, lst is a list but lst2 is a number. They’re not compatible.

Hope this helps.

1 Like