Python Forum

Full Version: Appending to list of list in For loop
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

I have question regarding for loops and appending to a list in that loop. In a for loop, I am trying to append a list to a list of lists. With each iteration, I modify one of the elements of the list. The code is listed below:

test = []
current = [0, 0]

for i in range(6):
    print('current value: {}'.format(current))
    test.append(current)
    current[0] += 1 #only increment the value at index 0

print('Test: {}'.format(test))
I print the current value with every iteration for testing purposes. The desired output is Test: [[0, 0], [1, 0], [2, 0], [3, 0], [4, 0], [5, 0]]. However, running the code yields the following:
Output:
current value: [0, 0] current value: [1, 0] current value: [2, 0] current value: [3, 0] current value: [4, 0] current value: [5, 0] Test: [[6, 0], [6, 0], [6, 0], [6, 0], [6, 0], [6, 0]]
It seems like the current value is correctly incremented, however the final output (test) is a list of lists containing only the last value taken by current.

Can anyone explain this behaviour, or how I could get the desired output?

Thanks,
Nicolas
current is a (mutable) list. When you append it to test each time, you are appending the same object. When you change one of the values of that object on line 7, all the views of that object are changed also.

You want to have 6 different lists in test, not 6 instances of the same list.

You could append a copy of that list. Some options:
from copy import copy
test.append(copy(current))
# or
test.append(list(current))
Thanks for your reply! Makes sense now and fixed my code!