A matrix is a way to organize numbers in a rectangular grid made up of rows and columns. We can assume it like a table, where:
- Rows go across (left to right)
- Columns go down (top to bottom)
The size of a matrix is defined by the number of rows (m) and columns (n). If a matrix has 3 rows and 4 columns, it’s called a 3×4 matrix.
Matrices are used in:
- Solving linear equations
- Image transformations (rotations, scaling)
- Machine learning algorithms
- Data representation
In this tutorial, we’ll explore different ways to create and work with matrices in Python, including using the NumPy library for matrix operations.

Visual representation of a matrix
Creating a simple matrix using Python
Method 1: Creating a matrix with a List of list
A Matrix is fundamentally a 2D list therefore we can create a Matrix by creating a 2D list (list of lists).
Python
mat = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]]
print("Matrix =", mat)
OutputMatrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
Method 2: Take Matrix input from user in Python
In this example we are going to take user inputs for rows and columns for the matrix and then print the complete matrix.
Python
rows = int(input("rows: "))
col = int(input("columns: "))
matrix = []
print("entries row-wise:")
for i in range(rows):
row = []
for j in range(col):
row.append(int(input())) # user input for rows
matrix.append(row) # adding rows to the matrix
print("\n2D matrix is:")
for i in range(rows):
for j in range(col):
print(matrix[i][j], end=" ")
print()
Output:
Enter the number of rows: 2
Enter the number of columns: 2
Enter the entries row-wise:
1
2
3
4
The 2D matrix is:
1 2
3 4
Method 3: Create a matrix using list comprehension
List comprehension is an elegant way to define and create a list in Python, we are using the range function for printing 4 rows and 4 columns.
Python
matrix = [[col for col in range(4)] for row in range(4)]
print(matrix)
Output[[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]
Explanation:
- Outer loop (for row in range(4)) runs 4 times to create 4 rows.
- Inner loop (for col in range(4)) fills each row with values 0 to 3.
Assigning Value in a matrix
Method 1: Assign value to an individual cell in Matrix
Here we are replacing and assigning value to an individual cell (1 row and 1 column = 11) in the Matrix.
Python
x = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
x[1][1] = 11
print(x)
Output[[1, 2, 3], [4, 11, 6], [7, 8, 9]]
Method 2: Using Negative Indexing
We are assigning a value to an individual cell using negative indexing in this example (-2 row and -1 column = 21) in the Matrix.
Python
x = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
x[-2][-1] = 21 # row = -2 , column = -1
print(x)
Output:
[[1, 2, 3], [4, 5, 21], [7, 8, 9]]
Accessing Value in a matrix
Method 1: Direct Indexing
We can access elements of a Matrix by using its row and column index.
Python
print("Element at (1,3):", x[0][2])
print("Element at (3,3):", x[2][2])
Output:
Element at (1,3): 3
Element at (3,3): 9
Method 2: Negative Indexing
Here, we are accessing elements of a Matrix by passing its row and column on negative indexing.
Python
Output:
8
Mathematical Operations with Matrix in Python
Example 1: Addition Using Loops
Let’s see how we can add two matrices using for-loop in Python.
Python
x = [[1, 2, 3],[4, 5, 6],[7, 8, 9]]
y = [[9, 8, 7],[6, 5, 4],[3, 2, 1]]
res = [[0]*3 for _ in range(3)]
for i in range(len(x)):
for j in range(len(x[0])):
res[i][j] = x[i][j] + y[i][j]
for r in res:
print(r)
Output:
[10, 10, 10]
[10, 10, 10]
[10, 10, 10]
Example 2: Addition & Subtraction with List Comprehension
Performing the Basic addition and subtraction using list comprehension.
Python
x = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
y = [[9, 8, 7],
[6, 5, 4],
[3, 2, 1]]
# Matrix addition
add_res = [[x[i][j] + y[i][j] for j in range(len(x[0]))] for i in range(len(x))]
# Matrix subtraction
sub_res = [[x[i][j] - y[i][j] for j in range(len(x[0]))] for i in range(len(x))]
print("Matrix Addition:")
for row in add_res:
print(row)
print("\nMatrix Subtraction:")
for row in sub_res:
print(row)
Output:
Matrix Addition
[10, 10, 10]
[10, 10, 10]
[10, 10, 10]
Matrix Subtraction
[-8, -6, -4]
[-2, 0, 2]
[4, 6, 8]
Example 3: Python program to multiply and divide two matrices
Performing the basic multiplication and division of two matrices using Python loop.
Python
x = [[2, 4, 6],
[8, 10, 12],
[14, 16, 18]]
y = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
# Element-wise multiplication
mult_res = [[x[i][j] * y[i][j] for j in range(3)] for i in range(3)]
# Element-wise integer division
div_res = [[x[i][j] // y[i][j] for j in range(3)] for i in range(3)]
print("Matrix Multiplication:")
for row in mult_res:
print(row)
print("\nMatrix Division:")
for row in div_res:
print(row)
Output:
Matrix Multiplication:
[2, 8, 18]
[32, 50, 72]
[98, 128, 162]
Matrix Division:
[2, 2, 2]
[2, 2, 2]
[2, 2, 2]
Transpose of a Matrix
Example 1: Using loop
Transpose of a matrix is obtained by changing rows to columns and columns to rows. In other words, transpose of A[][] is obtained by changing A[i][j] to A[j][i].
Python
x = [[9, 8, 7], [6, 5, 4], [3, 2, 1]]
transpose = [[0]*3 for _ in range(3)]
for i in range(len(x)):
for j in range(len(x[0])):
transpose[j][i] = x[i][j]
for r in transpose:
print(r)
Output[9, 6, 3]
[8, 5, 2]
[7, 4, 1]
Example 2: Using List Comprehension
Here’s how to Transpose a matrix using list comprehension.
Python
transpose = [[x[j][i] for j in range(len(x))] for i in range(len(x[0]))]
for row in transpose:
print(row)
Output:
[9, 6, 3]
[8, 5, 2]
[7, 4, 1]
NumPy Matrix Operations
Creating a Matrix with Random Values
Here we are creating a Numpy array using numpy.random and a random module.
Python
import numpy as np
arr = np.random.randint(10, size=(3, 3))
print(arr)
Output:
[[2 7 5]
[8 5 1]
[8 4 6]]
Explanation:
- The numpy.random module is used to generate random numbers.
- np.random.randint(10, size=(3, 3)) creates a 3×3 matrix with random integers from 0 to 9.
Basic Math Operations with NumPy
Here we are covering different mathematical operations such as addition, subtraction, multiplication, and division using Numpy.
Python
import numpy as np
x = np.array([[1, 2], [4, 5]])
y = np.array([[7, 8], [9, 10]])
print("Addition:\n", np.add(x, y))
print("Subtraction:\n", np.subtract(x, y))
print("Multiplication:\n", np.multiply(x, y))
print("Division:\n", np.divide(x, y))
OutputAddition:
[[ 8 10]
[13 15]]
Subtraction:
[[-6 -6]
[-5 -5]]
Multiplication:
[[ 7 16]
[36 50]]
Division:
[[0.14285714 0.25 ]
[0.44444444 0.5 ]]
Dot and cross product with Matrix
In this example, we are going to discuss how we can calculate the dot and the cross products of two matrices using NumPy, it provides built in functions to calculate them. First, let’s discsuss what are dot and cross products in short:
- Dot Product: Calculates the sum of the products of corresponding elements, often used to find projections or perform matrix multiplication.
- Cross Product: Produces a vector perpendicular to two 3D vectors, useful in physics for torque, angular momentum, etc.
Python
import numpy as np
x = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
y = [[9, 8, 7], [6, 5, 4], [3, 2, 1]]
print("Dot Product:\n", np.dot(x, y))
print("Cross Product:\n", np.cross(x, y))
OutputDot Product:
[[ 30 24 18]
[ 84 69 54]
[138 114 90]]
Cross Product:
[[-10 20 -10]
[-10 20 -10]
[-10 20 -10]]
Transpose Using NumPy
To perform transpose operation in matrix we can use the numpy.transpose() method.
Python
import numpy as np
matrix = [[1, 2, 3], [4, 5, 6]]
print(np.transpose(matrix))
Output[[1 4]
[2 5]
[3 6]]
Creating Empty Matrices
Initializing an empty array, using the np.zeros().
Python
import numpy as np
a = np.zeros((2, 2), dtype=int)
print("2x2 Matrix:\n", a)
b = np.zeros((3, 3))
print("3x3 Matrix:\n", b)
Output2x2 Matrix:
[[0 0]
[0 0]]
3x3 Matrix:
[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]
Slicing in Matrix using Numpy
Slicing is the process of choosing specific rows and columns from a matrix and then creating a new matrix by removing all of the non-selected elements.
Python
import numpy as np
x = np.array([[6, 8, 10],
[9, -12, 15],
[12, 16, 20],
[15, -20, 25]])
print("Full Matrix:\n", x)
print("Third Row, Second Column:", x[2:3, 1])
print("Third Row, Third Column:", x[2:3, 2])
OutputFull Matrix:
[[ 6 8 10]
[ 9 -12 15]
[ 12 16 20]
[ 15 -20 25]]
Third Row, Second Column: [16]
Third Row, Third Column: [20]
Deleting Rows with NumPy
Here, we are trying to delete rows using the np.delete() function. In the code, we first tried to delete the 0th row, then we tried to delete the 2nd row, and then the 3rd row.
Python
import numpy as np
a = np.array([[6, 8, 10],
[9, -12, 15],
[12, 16, 20],
[15, -20, 25]])
print("Delete 0th Row:\n", np.delete(a, 0, axis=0))
print("Delete 1st Row:\n", np.delete(a, 1, axis=0))
OutputDelete 0th Row:
[[ 9 -12 15]
[ 12 16 20]
[ 15 -20 25]]
Delete 1st Row:
[[ 6 8 10]
[ 12 16 20]
[ 15 -20 25]]
Add Rows or Columns to a NumPy Array
We can easily add a new row or column to an existing NumPy array using stacking functions like np.hstack() (horizontal stack) and np.vstack() (vertical stack).
Here’s how to add a column to an existing 2D array:
Python
import numpy as np
x = np.array([[6, 8, 10],
[9, -12, 15],
[15, -20, 25]])
# new column to be added
col = np.array([1, 2, 3])
# add the column (after reshaping it into a column vector)
res = np.hstack((x, np.atleast_2d(col).T))
print("Resultant Array:\n", res)
OutputResultant Array:
[[ 6 8 10 1]
[ 9 -12 15 2]
[ 15 -20 25 3]]
Similar Reads
numpy.matrix() in Python
This class returns a matrix from a string of data or array-like object. Matrix obtained is a specialised 2D array. Syntax : numpy.matrix(data, dtype = None) : Parameters : data : data needs to be array-like or string dtype : Data type of returned array. Returns : data interpreted as a matrix # Pytho
1 min read
Python | Numpy matrix.put()
With the help of Numpy matrix.put() method, we can put the value by passing index and value in a given matrix. Syntax : matrix.put(index, value) Return : Return new matrix Example #1 : In this example we can see that we are able to put the value from in given matrix with the help of method matrix.pu
1 min read
Python | Numpy matrix.sum()
With the help of matrix.sum() method, we are able to find the sum of values in a matrix by using the same method. Syntax : matrix.sum() Return : Return sum of values in a matrix Example #1 : In this example we are able to find the sum of values in a matrix by using matrix.sum() method. # import the
1 min read
Python | Numpy matrix.dot()
With the help of Numpy matrix.dot() method, we are able to find a product of two given matrix and gives output as new dimensional matrix. Syntax : matrix.dot() Return : Return product of two matrix Example #1 : In this example we can see that with the help of matrix.dot() method we are able to find
1 min read
Python | Numpy matrix.max()
With the help of Numpy matrix.max() method, we can get the maximum value from given matrix. Syntax : matrix.max() Return : Return maximum value from given matrix Example #1 : In this example we can see that we are able to get the maximum value from a given matrix with the help of method matrix.max()
1 min read
numpy.asmatrix() in Python
numpy.asmatrix(data, dtype = None) Returns a matrix by interpreting the input as a matrix. Parameters : data : array-like input data dtype : Data type of returned array Returns : Interprets the input as a matrix # Python Programming illustrating # numpy.asmatrix import numpy as geek # array-like inp
1 min read
Python | Numpy matrix.copy()
With the help of Numpy matrix.copy() method, we can make a copy of all the data elements that is present in matrix. If we change any data element in the copy, it will not affect the original matrix. Syntax : matrix.copy() Return : Return copy of matrix Example #1 : In this example we can see that wi
1 min read
Python | Numpy matrix.take()
With the help of Numpy matrix.take() method, we can select the elements from a given matrix by passing the parameter as index value of that element. It will return a matrix having one dimension. Remember it will work for one axis at a time. Syntax : matrix.take(index, axis) Return : Return matrix of
1 min read
Python | Numpy matrix.fill()
With the help of Numpy matrix.fill() method, we are able to fill a scalar value in a given matrix and gives output as matrix having scalar values. Syntax : matrix.fill(value) Return : Return a matrix having scalar value Example #1 : In this example we can see that with the help of matrix.fill() meth
1 min read
Python | Numpy matrix.item()
With the help of Numpy matrix.item() method, we can get the items from a given matrix by just providing index number and for multidimensional matrix we get the item by giving tuple of index value. Syntax : matrix.item(index) Return : Return item from given matrix Example #1 : In this example we can
1 min read