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?
Submitted by IncludeHelp, on March 26, 2020

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 matrix elements

Just like matrix in C/C++, we can access the elements in Python also.

Consider the below program,

# 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

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 





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.