pythonlistappend

Appending to a list by adding to the previous value in Python


I have some repeat scenarios where I have an initial list, then I want to add some additional values to the end of the list by taking the last value and adding a constant to it.

I want to repeat this for some x amount of times, taking the previous list value and adding the same constant to it.

I'm quite new to Python and I have got a working approach per below. I feel like I need the interator 'index' so that I can call the previous item in the list. It means the "items" variable is literally doing nothing which has me thinking that there would be a better way to do this. Any suggestions?

starting_list = [1, 5, 3]
increment = 7

additional_items = 5

for index, items in enumerate(range(additional_items), start=3):
    starting_list.append(starting_list[index - 1] + increment)

print(starting_list)

this gives me the desired output per below:

[1, 5, 3, 10, 17, 24, 31, 38]

Solution

  • by taking the last value and adding a constant to it

    You can get the last value of the list using starting_list[-1]. This removes the need for the index variable altogether, simplifying the code like this:

    starting_list = [1, 5, 3]
    increment = 7
    
    additional_items = 5
    
    for _ in range(additional_items):
        starting_list.append(starting_list[-1] + increment)
    
    print(starting_list)