Transpose matrix python without numpy

Simple loops way:

matrix = [[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3]]  

print([[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))])
# [[1, 1, 1, 1, 1, 1, 1], [2, 2, 2, 2, 2, 2, 2], [3, 3, 3, 3, 3, 3, 3]]

Or zip:

matrix = [[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3]]

print(list(map(list, zip(*matrix))))
# [[1, 1, 1, 1, 1, 1, 1], [2, 2, 2, 2, 2, 2, 2], [3, 3, 3, 3, 3, 3, 3]]

In this article, we will understand how to do transpose a matrix without NumPy in Python. So, first, we will understand how to transpose a matrix and then try to do it not using NumPy.

What is the Transpose of a Matrix?

Matrix is the representation of an array size in rectangular filled with symbols, expressions, alphabets and numbers arranged in rows and columns.

Now, we have to know what is the transpose of a matrix?

The matrix whose row will become the column of the new matrix and column will be the row of the new matrix. Therefore, we can implement this with the help of Numpy as it has a method called transpose().

Let’s implement with the help of NumPy:

PROGRAM CODE:

import numpy as np

arr1 = np.array([[1, 2, 3], [4, 5, 6]])

print(f'Original Array:\n{arr1}')

arr1_transpose = arr1.transpose()

print(f'Transposed Array:\n{arr1_transpose}')

OUTPUT:

Original Array:
[[1 2 3]
[4 5 6]]
Transposed Array:
[[1 4]
[2 5]
[3 6]]

But, we have already mentioned that we cannot use the Numpy. So, we can use plain logics behind this concept. Therefore, we can use nested loops to implement this. After that, we can swap the position of rows and columns to get the new matrix. Then, the new matrix is generated.

PROGRAM CODE:

Se our new Python code below:

X = [[12,7],
    [4 ,5],
    [3 ,8]]

result = [[0,0,0],
         [0,0,0]]

# iterate through rows
for i in range(len(X)):
   # iterate through columns
   for j in range(len(X[0])):
       result[j][i] = X[i][j]

for r in result:
   print(r)

OUTPUT: 

[12, 4, 3]
[7, 5, 8]

Explanation:

In this program, we have seen that we have used two for loops to implement this. So, the time complexity of the program is O(n^2). But, we can reduce the time complexity with the help of the function called transpose() present in the NumPy library.

For details, you can check this article.

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    Transpose of a matrix is a task we all can perform very easily in python (Using a nested loop). But there are some interesting ways to do the same in a single line.
    In Python, we can implement a matrix as nested list (list inside a list). Each element is treated as a row of the matrix. For example m = [[1, 2], [4, 5], [3, 6]] represents a matrix of 3 rows and 2 columns.
    First element of the list – m[0] and element in first row, first column – m[0][0].

    1. Using Nested List Comprehension: Nested list comprehension are used to iterate through each element in the matrix. In the given example, we iterate through each element of matrix (m) in column major manner and assign the result to rez matrix which is the transpose of m.

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

      for row in m :

          print(row)

      rez = [[m[j][i] for j in range(len(m))] for i in range(len(m[0]))]

      print("\n")

      for row in rez:

          print(row)

      Output:

      [1, 2]
      [3, 4]
      [5, 6]
      
      
      [1, 3, 5]
      [2, 4, 6]
      
    1. Using zip: Zip returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. In this example we unzip our array using * and then zip it to get the transpose.

      matrix=[(1,2,3),(4,5,6),(7,8,9),(10,11,12)]

      for row in matrix:

          print(row)

      print("\n")

      t_matrix = zip(*matrix)

      for row in t_matrix:

          print(row)

      Output:

      (1, 2, 3)
      (4, 5, 6)
      (7, 8, 9)
      (10, 11, 12)
      
      (1, 4, 7, 10)
      (2, 5, 8, 11)
      (3, 6, 9, 12)
      

      Note :- If you want your result in the form [[1,4,7,10][2,5,8,11][3,6,9,12]] , you can use t_matrix=map(list, zip(*matrix)).

    1. Using numpy: NumPy is a general-purpose array-processing package designed to efficiently manipulate large multi-dimensional arrays. The transpose method returns a transposed view of the passed multi-dimensional matrix.

      import numpy 

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

      print(matrix)

      print("\n")

      print(numpy.transpose(matrix))

      Or, simply using “.T” after the variable

      import numpy as np

      matrix = np.array([[1,2,3],[4,5,6]])

      print(matrix)

      print("\n")

      print(matrix.T)

      Output:

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

      Note :- “.T” only works on numpy arrays

    This article is contributed by Mayank Rawat & simply modified by Md. Tahmid Hasan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to . See your article appearing on the GeeksforGeeks main page and help other Geeks.

    Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.


    How do you transpose a matrix in Python?

    Transpose of a matrix is obtained by changing rows to columns and columns to rows. In other words, transpose of A[][] is obtained by changing A[i][j] to A[j][i]. For Square Matrix: The below program finds transpose of A[][] and stores the result in B[][], we can change N for different dimension.

    How do you get the transpose of a matrix using NumPy in Python?

    NumPy How to Transpose a Matrix.
    import numpy as np..
    A = np. array([[1, 2], [3, 4]]).
    A_T = A. transpose().
    print(A_T).

    Can you transpose a list in Python?

    You can transpose a two-dimensional list using the built-in function zip() . zip() is a function that returns an iterator that summarizes the multiple iterables ( list , tuple , etc.). In addition, use * that allows you to unpack the list and pass its elements to the function.

    Can Python handle matrices?

    In python matrix can be implemented as 2D list or 2D Array. Forming matrix from latter, gives the additional functionalities for performing various operations in matrix. These operations and array are defines in module “numpy“.