0

I'm attempting to iterate through a list of 3 items, subtracting an amount from alternating items on each iteration, and appending the result to a new list, until each number in the list is 0.

What's really weird is that when printing the new list, the results are exactly what I want, but using the append method does not result in the desired behavior.

I've tried moving the append statement all over the place and think I may need a nested for loop, but I'm not even sure what I could iterate through in that loop.

Here's the code I got.

amt_list = [10,10,10]
ctr = 0
days = []
in_ctr = 0


while any(value > 0 for value in amt_list):
    for d in amt_list:
        in_ctr += 1
        amt_list[in_ctr - 1] = d - 0.5
        print(amt_list)
        print(in_ctr)       
        if in_ctr == 3:
            in_ctr = 0
        days.append(amt_list)
    ctr += 1
    if (ctr - 1) == 2:
        ctr = 0
    print(days)


print(amt_list)

Here's the output:

[9.5, 10, 10]
1
[9.5, 9.5, 10]
2
[9.5, 9.5, 9.5]
3
[[9.5, 9.5, 9.5], [9.5, 9.5, 9.5], [9.5, 9.5, 9.5]][9.0, 9.5, 9.5]
1
[9.0, 9.0, 9.5]
2
[9.0, 9.0, 9.0]
3
[[9.0, 9.0, 9.0], [9.0, 9.0, 9.0], [9.0, 9.0, 9.0], [9.0, 9.0, 9.0], [9.0, 9.0, 9.0], [9.0, 9.0, 9.0]][8.5, 9.0, 9.0]

What i am aiming to accomplish is a final list with..

amt_list = [[9.5, 10, 10], [9.5, 9.5, 10], [9.5, 9.5, 9.5]..., ..., [0, 0, 0.5]]
  • > "until each number in the list is 0." but you still have ```0.5``` last sub list of your expected output ```[0, 0, 0.5]```. please clerify – shivankgtm Jan 21 '22 at 12:21
  • 1
    You must do `days.append(list(amt_list))` instead of `days.append(amt_list)`. Otherwise you always work and update the same list. – qouify Jan 21 '22 at 12:23
  • 1
    `days.append(amt_list)` adds _the reference_ to a list to `days`. All references point to the same list data. You need to copy values to create a new, seperate list and add that - not add the same list(reference) over and over – Patrick Artner Jan 21 '22 at 12:25
  • `if in_ctr == 3: in_ctr = 0` == `in_ctr = in_ctr %3` – Patrick Artner Jan 21 '22 at 12:27

0 Answers0