Today we’ll learn how to use list comprehensions to work with matrices. In particular we’ll be talking about matrix column and diagonal retrieval with list comprehensions.
You can read this article if you want to learn more about list comprehensions.
In mathematics a matrix is a rectangular array of numbers arranged in rows and columns. If the number of rows is the same as the number of columns, we have a square matrix.
Here’s what a matrix looks like in math:
Although we can use specialized modules to work with matrices, like numpy, for the most basic scenarios we can just use lists. A matrix can be represented as a list of lists. Here’s an example:
A = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
Each sublist in the A list represents one row. What we now want to do is retrieve the middle column and both diagonals. We can use list comprehensions to do that.
Retrieving the Middle Matrix Column
Let’s start with the middle matrix column:
>>> [row[1] for row in A]
[2, 5, 8]
Retrieving the Diagonals
And now let’s retrieve the diagonal from the upper left corner to the lower right corner:
>>> [A[i][i] for i in range(len(A))]
[1, 5, 9]
And now the other diagonal, from the upper right corner to the lower left corner:
>>> [A[i][len(A) - 1 - i] for i in range(len(A))]
[3, 5, 7]
Transposing a Matrix
We can also use a list comprehension to transpose a matrix. To transpose a matrix means to create a new matrix where the rows are the columns of the original matrix.
Here’s how it looks in math:
And here’s how you can do it in code using a list comprehension:
>>> transpose = [[row[i] for row in A] for i in range(len(A))]
>>> transpose
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Here’s the video version of the article: