time_count = [[0, 0, 0, 0]] * 4
j = 0
for i in range(len(time_count)):
time_count[i][1] = j
j += 1
print(time_count)
Output:
[[0, 3, 0, 0], [0, 3, 0, 0], [0, 3, 0, 0], [0, 3, 0, 0]]
I would expect the output to be like:
[[0,0,0,0],[0,1,0,0],[0,2,0,0],[0,3,0,0]]
can someone explain why every index[1]
is 3
?
Easy fix:
time_count = [[0, 0, 0, 0] for _ in range(4)]
As Klaus D. has alluded, using the *
operator on nested lists is usually a bad idea, as it duplicates the contents by copying the references. You won't notice this when multiplying sequences of immutable types, e.g. a list of integers, but when the elements are mutable, you get duplicates.
It's not good to write a list as [[0, 0, 0, 0]]*4. Lists are mutable. Each time you change any of the list elements all the copies of it will change. one good way to write is as below because that way you are not copying list elements.
[[0, 0, 0, 0] for i in range(4)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With