Matrix Transpose in Python

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In linear algebra, the transpose of a matrix is an operator which flips a matrix over its diagonal. The transpose of a matrix is obtained by exchanging its rows into columns. In Python, we can transpose a two-dimensional list using a simple one-liner code.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/PythonStandardLibraryGroup -.-> python/data_collections("`Data Collections`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-13735{{"`Matrix Transpose in Python`"}} python/variables_data_types -.-> lab-13735{{"`Matrix Transpose in Python`"}} python/lists -.-> lab-13735{{"`Matrix Transpose in Python`"}} python/tuples -.-> lab-13735{{"`Matrix Transpose in Python`"}} python/function_definition -.-> lab-13735{{"`Matrix Transpose in Python`"}} python/data_collections -.-> lab-13735{{"`Matrix Transpose in Python`"}} python/build_in_functions -.-> lab-13735{{"`Matrix Transpose in Python`"}} end

Transpose Matrix

Write a function called transpose(lst) that takes a two-dimensional list as an argument and returns the transpose of the given list.

Follow these steps to solve the problem:

  • Use *lst to get the provided list as tuples.
  • Use zip() in combination with list() to create the transpose of the given two-dimensional list.
def transpose(lst):
  return list(zip(*lst))
transpose([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
## [(1, 4, 7, 10), (2, 5, 8, 11), (3, 6, 9, 12)]

Summary

In this challenge, you learned how to transpose a two-dimensional list using Python. The transpose of a matrix is obtained by exchanging its rows into columns. You can use this technique to manipulate data in a variety of applications, such as data analysis and machine learning.

Other Python Tutorials you may like