Python Matrices and NumPy Arrays

A matrix is a two-dimensional data structure where numbers are arranged into rows and columns. For example:

Matrix with 4 columns and 3 rows

This matrix is a 3x4 (pronounced "three by four") matrix because it has 3 rows and 4 columns.


Python Matrix

Python doesn't have a built-in type for matrices. However, we can treat a list of a list as a matrix. For example:

A = [[1, 4, 5], 
    [-5, 8, 9]]

We can treat this list of a list as a matrix having 2 rows and 3 columns.

Python Matrix Example

Be sure to learn about Python lists before proceed this article.


Let's see how to work with a nested list.

A = [[1, 4, 5, 12], 
    [-5, 8, 9, 0],
    [-6, 7, 11, 19]]

print("A =", A) 
print("A[1] =", A[1])      # 2nd row
print("A[1][2] =", A[1][2])   # 3rd element of 2nd row
print("A[0][-1] =", A[0][-1])   # Last element of 1st Row

column = [];        # empty list
for row in A:
  column.append(row[2])   

print("3rd column =", column)

When we run the program, the output will be:

A = [[1, 4, 5, 12], [-5, 8, 9, 0], [-6, 7, 11, 19]]
A[1] = [-5, 8, 9, 0]
A[1][2] = 9
A[0][-1] = 12
3rd column = [5, 9, 11]

Here are few more examples related to Python matrices using nested lists.