You might remember this from math class, but if even if you don't, it should still be pretty easy to follow along. We've already gone over matrices and how to use them in Python, and today we're going to talk about how you can super quickly and easy transpose a matrix. When you transpose a matrix, you're turning its columns into its rows. This is easier to understand when you see an example of it, so check out the one below.
Let's say that your original matrix looks like this:
x = [[1,2][3,4][5,6]]
In that matrix, there are two columns. The first is made up of 1, 3 and 5, and the second is 2, 4, and 6. When you transpose the matrix, the columns become the rows. So a transposed version of the matrix above would look as follows:
y = [[1,3,5][2,4,6]]
So the result is still a matrix, but now it's organized differently, with different values in different places.
To transposes a matrix on your own in Python is actually pretty easy. It can be done really quickly using the built-in zip function. Here's how it would look:
matrix = [[1,2][3.4][5,6]] zip(*matrix)
Your output for the code above would simply be the transposed matrix. Super easy.
You can also transpose a matrix using NumPy, but in order to do that, NumPy has to be installed, and it's a little bit more of a clunkier way of achieving the same goal as the zip function achieves very quickly and easily.
Now that you understand what transposing matrices is and how to do it for yourself, give it a try in your own code, and see what types of versatility and functionalities it adds to your own custom functions and code snippets. Understanding how to use and manipulate matrices can really add a lot of dimension to your coding skills, and it's a good tool to have in your back pocket.To Practice: Try this interactive course on the basics of Lists, Functions, Packages and NumPy in Python.