Transpose a Matrix in Python

(Last Updated On: 09/01/2023)

Python Program to Transpose a Matrix Using for Loop

# Python Program to Transpose a Matrix Using for Loop

matrix_x = [[1, 4],
     [2, 5],
     [3, 6]]

res = [[0, 0, 0],
          [0, 0, 0]]

# iterate matrix rows
for i in range(len(matrix_x)):
    # iterate matrix column of each row
    for j in range(len(matrix_x[0])):
        res[j][i] = matrix_x[i][j]

for i in res:
   print(i)

Output:

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

Leave a Reply

Your email address will not be published. Required fields are marked *