0
def append_sum(lst):
  new_num = (lst[-1]+lst[-2])
  lst.append(new_num)
  new_num1 = (lst[-1]+lst[-2])
  lst.append(new_num1)
  new_num2 = (lst[-1]+lst[-2])
  lst.append(new_num2)
  return lst

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

this prints [1, 1, 2, 3, 5, 8] but how do I do it N times?

And what is this "codes" actually called in coding? (I'm referring to the code that is in the function)

Titus
  • 13
  • 2

1 Answers1

0

You can do that single operation N times just by doing:

for _ in range(N):
    lst.append(lst[-1] + lst[-2])

A full example:

def append_sum(lst, count):
    for _ in range(count):
        lst.append(lst[-1] + lst[-2])
    return lst

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

will generate:

[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • what is the difference between the "_" and " I" for the "for _ in range(count):" vs "for i in range(n):" (in the other guys comment) – Titus Nov 26 '20 at 10:19
  • @Titus: that's covered in far greater detail at https://stackoverflow.com/questions/5893163/what-is-the-purpose-of-the-single-underscore-variable-in-python than I could hope to do it justice in a comment. – paxdiablo Nov 26 '20 at 11:55