1

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

himika8201
  • 35
  • 3

1 Answers1

1

you can use slicing to do that.

n=3
twoD_array=[]
arr = [16,13,4,16,13,19,23,8,11]
for i in range(0,len(arr),n):
        twoD_array.append(arr[i:i+n])

print(twoD_array)
Shashikumar KL
  • 1,007
  • 1
  • 10
  • 25