I am trying to convert a python list into a 2d matrix without numpy library.
However, in doing so, my code is not working as expected.
n=3
arr = [16,13,4,16,13,19,23,8,11]
mat=[[0]*n]*n #initialising a 3*3 matrix
for a in range(n):
for b in range(n):
mat[a][b]=arr[b]
print(mat) #To understand the result of each iteration
if len(arr) >n:
arr=arr[n:]
print(mat)
The obtained output is:
[[16, 0, 0], [16, 0, 0], [16, 0, 0]]
[[16, 13, 0], [16, 13, 0], [16, 13, 0]]
[[16, 13, 4], [16, 13, 4], [16, 13, 4]]
[[16, 13, 4], [16, 13, 4], [16, 13, 4]]
[[16, 13, 4], [16, 13, 4], [16, 13, 4]]
[[16, 13, 19], [16, 13, 19], [16, 13, 19]]
[[23, 13, 19], [23, 13, 19], [23, 13, 19]]
[[23, 8, 19], [23, 8, 19], [23, 8, 19]]
[[23, 8, 11], [23, 8, 11], [23, 8, 11]]
finally:
[[23, 8, 11], [23, 8, 11], [23, 8, 11]]
instead of:
[[16,13,4], [16,13,19], [23, 8, 11]]
Why is the value of the entire column changing after each iteration instead of just that cell?
What possible change in the code can give the desired result(i.e- converting the list of 9 elements to a 3x3 matrix)?