Explain Python Matrix with examples


A matrix in Python is a two-dimensional array having a specific number of rows and columns. The data elements in Python matrix can be numbers, strings or symbols etc.

Matrix or two-dimensional list is an important data structure. Various operations associated with matrix involve transpose, addition or multiplication of two matrices.

We will discuss how to declare a matrix in python with a specific number of rows and columns and then input data items from the user and finally print the matrix.

Declare a matrix in Python as nested list

A matrix in Python can be declared as a nested list. The number of rows and columns needs to be specified. Suppose number of rows is 3 and number of columns is 4. We will declare the matrix as follows

Matrix=[[0]*4 for i in range(3)]

Input matrix elements and print them row-wise

Example

col=4
rows=3
matrix=[[0]*col for i in range(rows)]
for i in range(rows):
   print("Enter","row",i+1,"elements")
   for j in range(col):
      matrix[i][j]=int(input())

def rowvise(matrix):
   for i in range(rows):
      print(matrix[i])
print("print as nested list")
print(matrix)
print("print each row in separate line")
rowvise(matrix)

Output

Enter row 1 elements
1
2
3
4
Enter row 2 elements
5
6
7
8
Enter row 3 elements
1
2
3
4
print as nested list
[[1, 2, 3, 4], [5, 6, 7, 8], [1, 2, 3, 4]]
print each row in separate line
[1, 2, 3, 4]
[5, 6, 7, 8]
[1, 2, 3, 4]

These are the basic operations on matrix, which involve declaring a matrix, assigning data element values and printing a matrix. The other operations such as transpose can be achieved by applying specific logic to the given matrix.

Updated on: 11-Mar-2021

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements