Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python Program to Interchange Diagonals of Matrix
Next article icon

Python Program to find transpose of a matrix

Last Updated : 09 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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]. 

matrix-transpose

For Square Matrix: The below program finds transpose of A[][] and stores the result in B[][], we can change N for different dimension. 

Python3




# Python3 Program to find
# transpose of a matrix
 
N = 4
 
# This function stores
# transpose of A[][] in B[][]
 
def transpose(A,B):
 
 for i in range(N):
  for j in range(N):
   B[i][j] = A[j][i]
 
# driver code
A = [ [1, 1, 1, 1],
 [2, 2, 2, 2],
 [3, 3, 3, 3],
 [4, 4, 4, 4]]
 
 
B = A[:][:] # To store result
 
transpose(A, B)
 
print("Result matrix is")
for i in range(N):
 for j in range(N):
  print(B[i][j], " ", end='')
 print()
  
# This code is contributed by Anant Agarwal.
 
 
Output:
Result matrix is 1  2  3  4   2  2  3  4   3  3  3  4   4  4  4  4

Time Complexity: O(n2)
Auxiliary Space: O(n2)

For Rectangular Matrix: The below program finds transpose of A[][] and stores the result in B[][]. 

Python3




# Python3 Program to find
# transpose of a matrix
 
M = 3
N = 4
 
# This function stores
# transpose of A[][] in B[][]
 
def transpose(A, B):
 
 for i in range(N):
  for j in range(M):
   B[i][j] = A[j][i]
 
# driver code
A = [ [1, 1, 1, 1],
 [2, 2, 2, 2],
 [3, 3, 3, 3]]
 
 
# To store result
B = [[0 for x in range(M)] for y in range(N)]
 
transpose(A, B)
 
print("Result matrix is")
for i in range(N):
 for j in range(M):
  print(B[i][j], " ", end='')
 print() 
 
 
Output:
Result matrix is 1  2  3   1  2  3   1  2  3   1  2  3

Time Complexity: O(n*m)
Auxiliary Space: O(n*m)

In-Place for Square Matrix:

Python3




# Python3 Program to find
# transpose of a matrix
 
N = 4
 
# Finds transpose of A[][] in-place
def transpose(A):
 
 for i in range(N):
  for j in range(i+1, N):
   A[i][j], A[j][i] = A[j][i], A[i][j]
 
# driver code
A = [ [1, 1, 1, 1],
 [2, 2, 2, 2],
 [3, 3, 3, 3],
 [4, 4, 4, 4]]
 
transpose(A)
 
print("Modified matrix is")
for i in range(N):
 for j in range(N):
  print(A[i][j], " ", end='')
 print()
  
# This code is contributed by Anant Agarwal.
 
 
Output:
Modified matrix is 1  2  3  4   1  2  3  4   1  2  3  4   1  2  3  4

Time Complexity: O(n2)
Auxiliary Space: O(1)

Please refer complete article on Program to find transpose of a matrix for more details!

Approach#4: Using zip()

In this approach, zip(*matrix) is used to “unzip” the rows of the matrix and group the corresponding elements together. The * operator is used to pass the rows of the matrix as separate arguments to zip(). The resulting tuples are then converted back into lists using a list comprehension.

Algorithm

1. Define the matrix to be transposed.
2. Use the zip() function to group the corresponding elements of each row together and create tuples from them.
3. Convert each tuple back to a list using a list comprehension.
4. Store the resulting list of lists as the transposed matrix.
5. Print both the original and transposed matrices.

Python3




matrix = [[1, 1, 1, 1],
          [2, 2, 2, 2],
          [3, 3, 3, 3],
          [4, 4, 4, 4]]
 
transpose = [list(row) for row in zip(*matrix)]
 
print("Original Matrix:")
for row in matrix:
    print(row)
 
print("Transposed Matrix:")
for row in transpose:
    print(row)
 
 
Output
Original Matrix: [1, 1, 1, 1] [2, 2, 2, 2] [3, 3, 3, 3] [4, 4, 4, 4] Transposed Matrix: [1, 2, 3, 4] [1, 2, 3, 4] [1, 2, 3, 4] [1, 2, 3, 4]

Time Complexity:
The time complexity of this program is O(n^2) where n is the number of rows or columns in the matrix. This is because we need to access each element of the matrix exactly once to create the transposed matrix.

Space Complexity:
The space complexity of this program is also O(n^2). This is because we need to store the original matrix and the transposed matrix in memory, which both have n^2 elements. Additionally, we create temporary tuples during the transposition process, but these are discarded after they are converted back to lists.

METHOD 5:Using list comprehension 

APPROACH:

This program demonstrates how to find the transpose of a given matrix using a list comprehension.

ALGORITHM:

1.Initialize a 2D list A with the given matrix values.
2.Create a new 2D list result using a nested list comprehension.
3.In the inner list comprehension, iterate through the rows of A and extract the ith element from each row.
4.Append the extracted elements as a row to the result list.
5.Print the result matrix by iterating through each row and joining the elements with a space.

Python3




A = [[1, 1, 1, 1],
     [2, 2, 2, 2],
     [3, 3, 3, 3],
     [4, 4, 4, 4]]
 
result = [[row[i] for row in A] for i in range(len(A[0]))]
 
# Print the result
for row in result:
    print(' '.join([str(elem) for elem in row]))
 
 
Output
1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4

Time complexity: O(n^2) – as the program iterates through each element of the matrix A and creates a new matrix of the same size.

Auxiliary Space: O(n^2) – as the program creates a new matrix of the same size as A to store the transpose.



Next Article
Python Program to Interchange Diagonals of Matrix
author
kartik
Improve
Article Tags :
  • DSA
  • Matrix
  • Python Programs
  • Python matrix-program
Practice Tags :
  • Matrix

Similar Reads

  • Python program to add two matrices
    Prerequisite : Arrays in Python, Loops, List Comprehension Program to compute the sum of two matrices and then print it in Python. We can perform matrix addition in various ways in Python. Here are a two of them. Examples: Input : X= [[1,2,3], [4 ,5,6], [7 ,8,9]] Y = [[9,8,7], [6,5,4], [3,2,1]] Outp
    2 min read
  • Python Program to Interchange Diagonals of Matrix
    Given a square matrix of order n*n, you have to interchange the elements of both diagonals. Examples : Input : matrix[][] = {1, 2, 3, 4, 5, 6, 7, 8, 9} Output : matrix[][] = {3, 2, 1, 4, 5, 6, 9, 8, 7} Input : matrix[][] = {4, 2, 3, 1, 5, 7, 6, 8, 9, 11, 10, 12, 16, 14, 15, 13} Output : matrix[][] =
    2 min read
  • Python Program for Program to Print Matrix in Z form
    Given a square matrix of order n*n, we need to print elements of the matrix in Z form Examples: Input : mat[][] = {1, 2, 3, 4, 5, 6, 7, 8, 9} Output : 1 2 3 5 7 8 9Input : mat[][] = {5, 19, 8, 7, 4, 1, 14, 8, 2, 20, 1, 9, 1, 2, 55, 4} Output: 5 19 8 7 14 20 1 2 55 4 C/C++ Code # Python program to pr
    2 min read
  • Python program to Convert a Matrix to Sparse Matrix
    Converting a matrix to a sparse matrix involves storing only non-zero elements along with their row and column indices to save memory. Using a DictionaryConverting a matrix to a sparse matrix using a dictionary involves storing only the non-zero elements of the matrix, with their row and column indi
    2 min read
  • Python Program to Convert Matrix to String
    Program converts a 2D matrix (list of lists) into a single string, where all the matrix elements are arranged in row-major order. The elements are separated by spaces or any other delimiter, making it easy to represent matrix data as a string. Using List ComprehensionList comprehension provides a co
    2 min read
  • Python Program to check if a matrix is symmetric
    A square matrix is said to be a symmetric matrix if the transpose of the matrix is the same as the given matrix. The symmetric matrix can be obtained by changing row to column and column to row. Examples: Input : 1 2 3 2 1 4 3 4 3Output : Yes Input : 3 5 8 3 4 7 8 5 3Output : No Method 1: A Simple s
    3 min read
  • Python Program to Rotate Matrix Elements
    Given a matrix, clockwise rotate elements in it. Examples: Input 1 2 3 4 5 6 7 8 9 Output: 4 1 2 7 5 3 8 9 6 For 4*4 matrix Input: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Output: 5 1 2 3 9 10 6 4 13 11 7 8 14 15 16 12Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution.
    3 min read
  • Python Program to check Involutory Matrix
    Given a matrix and the task is to check matrix is an involutory matrix or not. Involutory Matrix: A matrix is said to be an involutory matrix if the matrix multiplies by itself and returns the identity matrix. The involutory matrix is the matrix that is its own inverse. The matrix A is said to be an
    3 min read
  • Python Program for Rotate a Matrix by 180 degree
    Given a square matrix, the task is that turn it by 180 degrees in an anti-clockwise direction without using any extra space. Examples : Input: 1 2 3 4 5 6 7 8 9 Output: 9 8 7 6 5 4 3 2 1Input: 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 Output: 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1Python Program for Rotate a Matrix b
    5 min read
  • Python Program to Multiply Two Matrices
    Given two matrices, we will have to create a program to multiply two matrices in Python. Example: Python Matrix Multiplication of Two-Dimension [GFGTABS] Python matrix_a = [[1, 2], [3, 4]] matrix_b = [[5, 6], [7, 8]] result = [[0, 0], [0, 0]] for i in range(2): for j in range(2): result[i][j] = (mat
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences