Home »
Python »
Python Programs
Python program to create matrix in Python
Here, we are going to learn how to create a matrix (two-dimensional array) in Python programming language?
By IncludeHelp Last updated : September 16, 2023
Creating Python Matrix
There is no specific data type in Python to create a matrix, we can use list of list to create a matrix.
Consider the below example,
mat = [
[10, 20, 30],
[40, 50, 60],
[70, 80, 80]
]
It can be considered a 3x3 matrix, there are 3 rows and 3 columns in 'mat' matrix.
Accessing Python Matrix Elements
Just like matrix in C/C++, we can access the elements in Python also.
Consider the below program,
Python program to create and print a matrix
# Python matrix creation
mat = [
[10, 20, 30],
[40, 50, 60],
[70, 80, 80]
]
# printing the matrix
print("mat: ", mat)
# printing rows
print("mat[0]: ", mat[0])
print("mat[1]: ", mat[1])
print("mat[2]: ", mat[2])
# printing specific elements
print("mat[0][0]: ", mat[0][0])
print("mat[0][1]: ", mat[0][1])
print("mat[0][2]: ", mat[0][2])
print("mat[1][0]: ", mat[1][0])
print("mat[1][1]: ", mat[1][1])
print("mat[1][2]: ", mat[1][2])
print("mat[2][0]: ", mat[2][0])
print("mat[2][1]: ", mat[2][1])
print("mat[2][2]: ", mat[2][2])
# printing matrix using loop (matrix form)
print("Matrix is: ")
for i in range(3):
for j in range(3):
print(mat[i][j], end = " ")
print() # prints new line
Output
The output of the above program is:
mat: [[10, 20, 30], [40, 50, 60], [70, 80, 80]]
mat[0]: [10, 20, 30]
mat[1]: [40, 50, 60]
mat[2]: [70, 80, 80]
mat[0][0]: 10
mat[0][1]: 20
mat[0][2]: 30
mat[1][0]: 40
mat[1][1]: 50
mat[1][2]: 60
mat[2][0]: 70
mat[2][1]: 80
mat[2][2]: 80
Matrix is:
10 20 30
40 50 60
70 80 80
Python Array Programs »