Skip to content
Home » Matrix Column and Diagonal Retrieval with List Comprehensions

Matrix Column and Diagonal Retrieval with List Comprehensions

Spread the love

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:

matrix column and diagonal retrieval

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]

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

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:

transposed matrix

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

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.

Here’s the video version of the article:


Spread the love

Leave a Reply