FAQ: Code Challenge: Lists - Append Sum


#1

This community-built FAQ covers the “Append Sum” exercise from the lesson “Code Challenge: Lists”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Computer Science
Data Science

FAQs on the exercise Append Sum

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!


#2

This challenge was comparatively far easier than some of the other challenges in this section. I simply got the sum of the last two elements and appended the list. Rinsed and repeated until finished. This seemed to be a little inefficient. I’m sure this will be covered in later lessons but my curiosity is getting the best of me. How would I build a loop that terminates after a finite number of runs?


#3

I was also curious, how to build a loop here, and this is what I came up with

def append_sum(lst):
  i = 0
  while i < 3:
    lst.append(lst[-2] + lst [-1])
    i += 1
  return lst

Changing the “3” will change the number of loops the code will run.


#4

We can use the input to derive the number of iterations:

while i < len(lst):

This way the list may be any length. We can also clone the list and iterate over that…

for _ in lst[:]:

An equivalent to this line,

lst.append(lst[-2] + lst[-1])

would be,

lst.append(sum(lst[-2:]))

Slightly off topic, what does this process remind one of (sum last two digits and append to list)? Hint: Fibonacci number sequence ring a bell?

def fibonacci_seq(n):
  fib = [1,1]
  for _ in ['']* (n - 2):
    fib.append(sum(fib[-2:]))
  return fib

print (fibonacci_seq(6))    # [1, 1, 2, 3, 5, 8]

#5

But did this work? I used the same code but the although the loop runs three times it only adds one element to the list

ps: found the error: in my code the return lst command was not indented…