Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I would expect the output to be like [[0,0,0,0,],[0,1,0,0],[0,2,0,0],[0,3,0,0]]

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 ?

like image 363
Sahas Avatar asked Jan 03 '23 00:01

Sahas


2 Answers

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.

like image 74
L3viathan Avatar answered Jan 11 '23 00:01

L3viathan


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)]
like image 27
nick Avatar answered Jan 11 '23 02:01

nick