Here we will discuss different ways how we can form a matrix using Python within this tutorial we will also discuss the various operation that can be performed on a matrix. we will also cover the external module Numpy to form a matrix and its operations in Python.

What is the matrix?
A matrix is a collection of numbers arranged in a rectangular array in rows and columns. In the fields of engineering, physics, statistics, and graphics, matrices are widely used to express picture rotations and other types of transformations.
The matrix is referred to as an m by n matrix, denoted by the symbol “m x n” if there are m rows and n columns.
Creating a simple matrix using Python
Method 1: Creating a matrix with a List of list
Here, we are going to create a matrix using the list of lists.
Python
matrix = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]]
print("Matrix =", matrix)
Output:
Matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
Method 2: Take Matrix input from user in Python
Here, we are taking a number of rows and columns from the user and printing the Matrix.
Python
Row = int(input("Enter the number of rows:"))
Column = int(input("Enter the number of columns:"))
# Initialize matrix
matrix = []
print("Enter the entries row wise:")
# For user input
# A for loop for row entries
for row in range(Row):
a = []
# A for loop for column entries
for column in range(Column):
a.append(int(input()))
matrix.append(a)
# For printing the matrix
for row in range(Row):
for column in range(Column):
print(matrix[row][column], end=" ")
print()
Output:
Enter the number of rows:2
Enter the number of columns:2
Enter the entries row wise:
5
6
7
8
5 6
7 8
Time Complexity: O(n*n)
Auxiliary Space: O(n*n)
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 = [[column for column 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]]
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]]
row = column = 1
X[row][column] = 11
print(X)
Output:
[[1, 2, 3], [4, 11, 6], [7, 8, 9]]
Method 2: Assign a value to an individual cell using negative indexing in Matrix
Here we are replacing and assigning value to an individual cell (-2 row and -1 column = 21) in the Matrix.
Python
row = -2
column = -1
X[row][column] = 21
print(X)
Output:
[[1, 2, 3], [4, 5, 21], [7, 8, 9]]
Accessing Value in a matrix
Method 1: Accessing Matrix values
Here, we are accessing elements of a Matrix by passing its row and column.
Python
print("Matrix at 1 row and 3 column=", X[0][2])
print("Matrix at 3 row and 3 column=", X[2][2])
Output:
Matrix at 1 row and 3 column= 3
Matrix at 3 row and 3 column= 9
Method 2: Accessing Matrix values using negative indexing
Here, we are accessing elements of a Matrix by passing its row and column on negative indexing.
Python
import numpy as np
X = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(X[-1][-2])
Output:
8
Mathematical Operations with Matrix in Python
Example 1: Adding values to a matrix with a for loop in python
Here, we are adding two matrices using the Python for-loop.
Python
# Program to add two matrices using nested loop
X = [[1, 2, 3],[4, 5, 6], [7, 8, 9]]
Y = [[9, 8, 7], [6, 5, 4], [3, 2, 1]]
result = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
# iterate through rows
for row in range(len(X)):
# iterate through columns
for column in range(len(X[0])):
result[row][column] = X[row][column]+ Y[row][column]
for r in result:
print(r)
Output:
[10, 10, 10]
[10, 10, 10]
[10, 10, 10]
Time Complexity: O(n*n)
Auxiliary Space: O(n*n)
Example 2: Adding and subtracting values to a matrix with list comprehension
Performing the Basic addition and subtraction using list comprehension.
Python
Add_result = [[X[row][column] + Y[row][column]
for column in range(len(X[0]))]
for row in range(len(X))]
Sub_result = [[X[row][column] - Y[row][column]
for column in range(len(X[0]))]
for row in range(len(X))]
print("Matrix Addition")
for r in Add_result:
print(r)
print("\nMatrix Subtraction")
for r in Sub_result:
print(r)
Output:
Matrix Addition
[10, 10, 10]
[10, 10, 10]
[10, 10, 10]
Matrix Subtraction
[-8, -6, -4]
[-2, 0, 2]
[4, 6, 8]
Time Complexity: O(n*n)
Auxiliary Space: O(n*n)
Example 3: Python program to multiply and divide two matrices
Performing the Basic multiplication and division using Python loop.
Python
rmatrix = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
for row in range(len(X)):
for column in range(len(X[0])):
rmatrix[row][column] = X[row][column] * Y[row][column]
print("Matrix Multiplication",)
for r in rmatrix:
print(r)
for i in range(len(X)):
for j in range(len(X[0])):
rmatrix[row][column] = X[row][column] // Y[row][column]
print("\nMatrix Division",)
for r in rmatrix:
print(r)
Output:
Matrix Multiplication
[9, 16, 21]
[24, 25, 24]
[21, 16, 9]
Matrix Division
[0, 0, 0]
[0, 1, 1]
[2, 4, 9]
Time Complexity: O(n*n)
Auxiliary Space: O(n*n)
Transpose in matrix
Example: Python Program to Transpose a Matrix 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]]
result = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
# iterate through rows
for row in range(len(X)):
# iterate through columns
for column in range(len(X[0])):
result[column][row] = X[row][column]
for r in result:
print(r)
# # Python Program to Transpose a Matrix using the list comprehension
# rez = [[X[column][row] for column in range(len(X))]
# for row in range(len(X[0]))]
# for row in rez:
# print(row)
Output:
[9, 6, 3]
[8, 5, 2]
[7, 4, 1]
Time Complexity: O(n*n)
Auxiliary Space: O(n*n)
Matrix using Numpy
Create a matrix using NumpyÂ
Here we are creating a Numpy array using numpy.random and a random module.
Python
import numpy as np
# 1st argument --> numbers ranging from 0 to 9,
# 2nd argument, row = 3, col = 3
array = np.random.randint(10, size=(3, 3))
print(array)
Output:
[[2 7 5]
[8 5 1]
[8 4 6]]
Matrix mathematical operations in Python Using Numpy
Here we are covering different mathematical operations such as addition subtraction, multiplication, and division using Numpy.
Python
# initializing matrices
x = numpy.array([[1, 2], [4, 5]])
y = numpy.array([[7, 8], [9, 10]])
# using add() to add matrices
print ("The element wise addition of matrix is : ")
print (numpy.add(x,y))
# using subtract() to subtract matrices
print ("The element wise subtraction of matrix is : ")
print (numpy.subtract(x,y))
print ("The element wise multiplication of matrix is : ")
print (numpy.multiply(x,y))
# using divide() to divide matrices
print ("The element wise division of matrix is : ")
print (numpy.divide(x,y))
Output:
The element wise addition of matrix is :
[[ 8 10]
[13 15]]
The element wise subtraction of matrix is :
[[-6 -6]
[-5 -5]]
The element wise multiplication of matrix is :
[[ 7 16]
[36 50]]
The element wise division of matrix is :
[[0.14285714 0.25 ]
[0.44444444 0.5 ]]
Dot and cross product with Matrix
Here, we will find the inner, outer, and cross products of matrices and vectors using NumPy in Python.
Python
X = [[1, 2, 3],[4, 5, 6],[7, 8, 9]]
Y = [[9, 8, 7], [6, 5, 4],[3, 2, 1]]
dotproduct = np.dot(X, Y)
print("Dot product of two array is:", dotproduct)
dotproduct = np.cross(X, Y)
print("Cross product of two array is:", dotproduct)
Output:
Dot product of two array is: [[ 30 24 18]
[ 84 69 54]
[138 114 90]]
Cross product of two array is: [[-10 20 -10]
[-10 20 -10]
[-10 20 -10]]
Matrix transpose in Python using Numpy
To perform transpose operation in matrix we can use the numpy.transpose() method.
Python
matrix = [[1, 2, 3], [4, 5, 6]]
print("\n", numpy.transpose(matrix))
Output:
[[1 4][2 5][3 6]]
Create an empty matrix with NumPy in Python
Initializing an empty array, using the np.zeros().
Python
a = np.zeros([2, 2], dtype=int)
print("\nMatrix of 2x2: \n", a)
c = np.zeros([3, 3])
print("\nMatrix of 3x3: \n", c)
Output:
Matrix of 2x2:
[[0 0]
[0 0]]
Matrix of 3x3:
[[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. In the first example, we are printing the whole matrix, in the second we are passing 2 as an initial index, 3 as the last index, and index jump as 1. The same is used in the next print we have just changed the index jump to 2.
Python
X = np.array([[6, 8, 10],
[ 9, -12, 15],
[ 12, 16, 20],
[ 15, -20, 25]])
# Example of slicing
# Syntax: Lst[ Initial: End: IndexJump ]
print(X[:])
print("\nSlicing Third Row-Second Column: ", X[2:3,1])
print("\nSlicing Third Row-Third Column: ", X[2:3,2])
Output:
[[ 6 8 10]
[ 9 -12 15]
[ 12 16 20]
[ 15 -20 25]]
Slicing Third Row-Second Column: [16]
Slicing Third Row-Third Column: [20]
Delete rows and columns using 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
# create an array with integers
# with 3 rows and 4 columns
a = np.array([[6, 8, 10],
[ 9, -12, 15],
[ 12, 16, 20],
[ 15, -20, 25]])
# delete 0 th row
data = np.delete(a, 0, 0)
print("data after 0 th row deleted: ", data)
# delete 1 st row
data = np.delete(a, 1, 0)
print("\ndata after 1 st row deleted: ", data)
# delete 2 nd row
data = np.delete(a, 2, 0)
print("\ndata after 2 nd row deleted: ", data)
Output:
data after 0 th row deleted:
[[ 9 -12 15]
[ 12 16 20]
[ 15 -20 25]]
data after 1 st row deleted:
[[ 6 8 10]
[ 12 16 20]
[ 15 -20 25]]
data after 2 nd row deleted:
[[ 6 8 10]
[ 9 -12 15]
[ 15 -20 25]]
Add row/columns in the Numpy array
We added one more column at the 4th position using np.hstack.Â
Python
ini_array = np.array([[6, 8, 10],
[9, -12, 15],
[15, -20, 25]])
# Array to be added as column
column_to_be_added = np.array([1, 2, 3])
# Adding column to numpy array
result = np.hstack((ini_array, np.atleast_2d(column_to_be_added).T))
# printing result
print("\nresultant array\n", str(result))
Output:
resultant array
[[ 6 8 10 1]
[ 9 -12 15 2]
[ 15 -20 25 3]]
Python – Matrix – FAQs
How to Create and Manipulate a Matrix in Python?
In Python, matrices can be created and manipulated using lists of lists or using libraries such as NumPy for more efficient and convenient matrix operations.
Creating a Matrix with Lists:
# Creating a matrix using nested lists
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
Manipulating a Matrix:
# Accessing elements
element = matrix[1][2] # Accessing the element at row 1, column 2 (6)
# Modifying elements
matrix[2][1] = 10 # Setting the element at row 2, column 1 to 10
What Are Python Tools for Matrix Multiplication?
For matrix multiplication, the NumPy library is commonly used due to its efficiency and simplicity.
Using NumPy for Matrix Multiplication:
import numpy as np
# Creating matrices using NumPy arrays
matrix1 = np.array([
[1, 2],
[3, 4]
])
matrix2 = np.array([
[5, 6],
[7, 8]
])
# Performing matrix multiplication
result = np.dot(matrix1, matrix2)
print(result)
Output:
[[19 22]
[43 50]]
How to Perform Matrix Inversion in Python?
Matrix inversion can be performed using NumPy’s inv function from the linalg module.
Example:
import numpy as np
# Creating a square matrix
matrix = np.array([
[1, 2],
[3, 4]
])
# Calculating the inverse
inverse_matrix = np.linalg.inv(matrix)
print(inverse_matrix)
Output:
[[-2. 1. ]
[ 1.5 -0.5]]
How to Access and Modify Matrix Elements in Python?
Matrix elements can be accessed and modified using indices. In NumPy, this is done similarly to accessing elements in a nested list.
Accessing and Modifying Elements:
import numpy as np
# Creating a matrix
matrix = np.array([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
])
# Accessing an element
element = matrix[1, 2] # Accessing the element at row 1, column 2 (6)
# Modifying an element
matrix[2, 1] = 10 # Setting the element at row 2, column 1 to 10
What Libraries Support Advanced Matrix Operations in Python?
Several libraries support advanced matrix operations in Python, including:
- NumPy: Provides support for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays.
- SciPy: Builds on NumPy and provides additional functionality for scientific and technical computing, including linear algebra, optimization, integration, and more.
- Pandas: Primarily used for data manipulation and analysis, but also supports operations on matrices through its DataFrame and Series objects.
- SymPy: A library for symbolic mathematics that includes functions for algebra, calculus, and other advanced mathematical operations, including matrix operations.
- TensorFlow and PyTorch: Libraries designed for machine learning that also include powerful matrix operation capabilities.
Similar Reads
Python - Matrix
Here we will discuss different ways how we can form a matrix using Python within this tutorial we will also discuss the various operation that can be performed on a matrix. we will also cover the external module Numpy to form a matrix and its operations in Python. What is the matrix?A matrix is a co
11 min read
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