Ad

I Would Expect The Output To Be Like [[0,0,0,0,],[0,1,0,0],[0,2,0,0],[0,3,0,0]]

08 August 2018 - 1 answer

``````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` ?

Ad

Answer

Basically, The entities of a list are pointers to a particular memory location. When one assigns list(a) to list(b) It implies that list(b) points to the same memory location as the list(a).

`````` a = [1, 2, 3]
b = a
a = [3, 4, 5]
print(a, b)

[3, 4, 5] [1, 2, 3]
``````

In the above-asked question if the inside of the nested list is multiplied by 4 times then all the sublists point to the same memory location. so, If one of the sublists is changed then the change is propagated to all of the sublists, Which basically creates unexpected results upon code execution. For anyone interested to know more, the video sums up all the basic features of lists that are not obvious. It also explains the above question in further detail. https://www.youtube.com/watch?v=_AEJHKGk9ns

Ad
source: stackoverflow.com
Ad