Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (19.9k points)

I tried the most basic approach for matrix transpose in python. However, I don't get the required results. Following by the code:

A = [ [1, 1, 1, 1], 

    [2, 2, 2, 2], 

    [3, 3, 3, 3], 

    [4, 4, 4, 4]] 

#print (A)

def TS (A):

    B = A

    for i in (range(len(A))):

        for j in (range(len(A))):

            A[i][j] = B [j][i]

TS(A)

#print (A)

for i in range(len(A)): 

    for j in range(len(A)): 

        print(B[i][j], " ", end='') 

    print() 

This is the result I get:

1  2  3  4  

2  2  3  4  

3  3  3  4  

4  4  4  4 

1 Answer

0 votes
by (25.1k points)

If you are familiar with numpy, you can do it like this:

import numpy as np 

z = np.transpose(np.array(A))

 

Or you can do it like this:

def  transpose (A):

B = [row[:] for row in A]

    for i in (range(len(A))):

    for j in (range(len(A))):

        B[i][j] = A[j][i]

    return B

Related questions

0 votes
1 answer
asked Oct 3, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
asked Sep 26, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
0 votes
1 answer
asked Mar 14, 2021 in Java by sheela_singh (9.5k points)
0 votes
2 answers
asked Jul 6, 2019 in Python by Sammy (47.6k points)

Browse Categories

...