Skip to content

Theory

Matrix

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

matrix

This matrix is a 3x4 matrix because it has 3 rows and 4 columns.

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

🐍 Python Script
A = [[1, 4, 5],
    [-5, 8, 9]]
We can treat this list of a list as a matrix having 2 rows and 3 columns

\(\begin{bmatrix}1 & 4 & 5\\-5 & 8 & 9\end{bmatrix}\)

Try the below code and play around with it to understand how you can create, manipulate and print a matrix in python.

🐍 Python Script
A = [[1, 4, 5, 2], 
    [5, 8, 9, 0],
    [6, 7, 1, 9]]

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)

print("Here is how to print a matrix in a nice way:")
for row in A:
  for elem in row:
    print(elem, end = '  ')
  print("\n")