General and very basic question

Hi There, Fellow Coders. In lists how to add last and before elements in a continuous list/append? Eg: My input: [1, 2, 3] with adding last two elements I get 5 (input[2]+[1]) How to continue or make last two elements add in a single list?

You mean you want to go from [1, 2, 3] to [1, 2, 3, 5]?

If so, consider the steps that you would take to do it yourself.

  • How do you access an element of a list?
  • How do you access the last element of a list?
  • How could you access the second to last element of a list?
  • Once you have the two elements, add them together.
  • Append that result to the end of the list.

Don’t get caught up in doing it all at once. Do each thing. Once you can do it at all, then you can consider how to refactor your code to make it more elegant if you like.


Good advice from @midlindner; keep it simple.

In some cases where you are working with several elements of a list, you could find it convenient to utilize slicing. See the following:

def append_sum_of_final_elements(lst, how_many_elements):
  if how_many_elements > len(lst):
    raise ValueError
    lst.append(sum(lst[-how_many_elements:])) # sum a slice of the list

my_numbers = [2, 9, 3, 8, 4, 7, 6] # appends 17
append_sum_of_final_elements(my_numbers, 3)


[2, 9, 3, 8, 4, 7, 6, 17]