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:
Can anyone explain this behaviour, or how I could get the desired output?
Thanks,
Nicolas
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
