Python Program: Read a Matrix

In this tutorial, you will learn how to take a 2D matrix input in Python 3.

We first write a couple of lines of code to intake the row and column dimensions of the matrix. The number of rows is assigned to m and the number of columns is assigned to n.

									  
				m = int(input("rows: "))
				n = int(input("columns: "))
				
			

After getting the row and column dimensions, we use a couple of for loops to read the elements that will form the matrix A[i,j] row-wise. As Python do not support arrays, we use list here to store the elements.

				
				a = []

				for i in range(m):
				    row =[]
				    for j in range(n):
				    	row.append(int(input('A[' + str(i) + ',' + str(j) +']: ')))
				    a.append(row)
				
			

You can also read or initialize the matrix in the following way:

				
			a = []

			for i in range(m):
			    a.append([])
			    for j in range(n):
			    	a[i].append(int(input('A[' + str(i) + ',' + str(j) +']: ')))
				
			

And now we lastly add some code to display the matrix. This is akin to printing a 2D array in Python.

				
				for i in range(m):
				    for j in range(n):
				        print(a[i][j], end = " ")
				    print()
				
			

Here is the full program.

				
				m = int(input("rows: "))
				n = int(input("columns: "))

				a = []

				for i in range(m):
				    row =[]
				    for j in range(n):
				    	row.append(int(input('A[' + str(i) + ',' + str(j) +']: ')))
				    a.append(row)

				print()

				for i in range(m):
				    for j in range(n):
				        print(a[i][j], end = " ")
				    print()
				
			

On executing the above program, it first prompts for the rows and columns dimensions of the matrix, and subsequently prompts for the matrix elements row-wise.

python program 2d matrix input

Notes

  • Python do not have support for Arrays, so we use Lists instead.