Index error while transposing matrix in script

Viewed 40

I have program that transposes a square matrix:

matrix = [[1, 2, 4], [3, 6, 9], [6, 8, 2]]
matrix _trans = []

for i in range (len (matrix)):
     for j in range (len (matrix)):
         matrix_trans [j] [i] = matrix [i] [j]

Error:

IndexError: list index out of range

Why is this error produced here?

2 Answers

The problem is that matrix_trans is just and empty list, that is why you can not access any indx, build a copy of matrix instead:

matrix = [[1, 2, 4], [3, 6, 9], [6, 8, 2]]
matrix_trans = [x[:] for x in matrix]

That happens because of matrix_trans[j][i], in the first iteration both j and i will be zero and matrix_trans is an empty list, so matrix_trans[0] would raise an index error, you should have a copy of your first matrix's dimensions in the strat, like this:

from copy import deepcopy
matrix = [[1, 2, 4], [3, 6, 9], [6, 8, 2]]
matrix_trans = deepcopy(matrix)

for i in range(len(matrix)):
     for j in range(len(matrix)):
         matrix_trans[j][i] = matrix[i][j]

result:

In [41]: matrix_trans
Out[41]: [[1, 3, 6], [2, 6, 8], [4, 9, 2]]

In [42]: matrix
Out[42]: [[1, 2, 4], [3, 6, 9], [6, 8, 2]]

for more information about copy module read Docs

Also, note that for this action you can use Python zip. like this:

list(zip(*matrix))
Related