Python: Sum Of The Final Two Numbers In A List, Then Append

Question:

For example lets say my input is 12, I am attempting to get the output of the lucas sequence to be [2 1 3 4 7 11], but instead I keep receiving the output of
[2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123, 199]. I’m attempting to get it to display the previous sequence number before my input, but I am struggling to find out.

This is my code

my_list = [2, 1]
input = 12

while len(my_list) in range(input):
    for i in my_list:
        second_to_last = my_list[-2]
        counter = i + second_to_last
    my_list.append(counter)

print(my_list)

Asked By: Fran_CS

||

Answers:

Your code runs while your list has less than 12 elements but your desired output implies that it should run while the last element is less than 12.

If you want to specify a maximal length, do this:

my_list = [2, 1]
max_length = 12

while len(my_list) < max_length:
    my_list.append(sum(my_list[-2:]))

print(my_list)
# [2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123, 199]

If you want a maximal last value, do that:

my_list = [2, 1]
max_last = 12

while my_list[-1] < max_last :
     my_list.append(sum(my_list[-2:]))
my_list.pop(-1)

print(my_list)
# [2, 1, 3, 4, 7, 11] 
Answered By: Guimoute

There’s no need for the for loop. You just need to add the last two elements, not all the elements.

And you want to stop if the new element to be added exceeds the limit, so add that check into the loop.

my_list = [2, 1]
limit = 12

while True:
    next_element = my_list[-1] + my_list[-2]
    if next_element >= limit:
        break
    my_list.append(next_element)

print(my_list)
Answered By: Barmar
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.