I tested the following python code on Spyder IDE. Thinking it would output 2d array q
as increasing number as 0..31 from q[0][0]
to q[3][7]>
q=[somelist]*4
creates a list with four identical items, the list somelist
. So, for example, q[0]
and q[1]
reference the same object.
Thus, in the nested for loop q[i]
is referencing the same list regardless of the value of i
.
To fix:
q = [[0]*8 for _ in range(4)]
The list comprehension evaluates [0]*8
4 distinct times, resulting in 4 distinct lists.
Here is a quick demonstration of this pitfall:
In [14]: q=[[0]*8]*4
You might think you are updating only the first element in the second row:
In [15]: q[1][0] = 100
But you really end up altering the first element in every row:
In [16]: q
Out[16]:
[[100, 0, 0, 0, 0, 0, 0, 0],
[100, 0, 0, 0, 0, 0, 0, 0],
[100, 0, 0, 0, 0, 0, 0, 0],
[100, 0, 0, 0, 0, 0, 0, 0]]