Shreya Srivastava
Shreya Srivastava

Reputation: 41

How to take matrix input from the user and display the matrix in Python?

I have an experience in java and c++ for 7 years now. I recently started learning python. Can someone please help me on how to read the input for the matrix and display the same in matrix format. This is the code I wrote:

import sys

# no of rows are equal to the number of columns.
n = int(input("Enter the number of rows in a matrix"))
a = [[0 for x in range (n)] for y in range(n)]
for i in range (n):
    for j in range(n):
        a[i][j]=int(input())
        print (a[i][j])
    print("\n")

Upvotes: 0

Views: 26404

Answers (8)

Daniel Abedini
Daniel Abedini

Reputation: 1

list = []
for i in range(3):
    list.append([])
    for j in range(3):
        list[i].append(2)
   
for i in range(3):
    for j in range(3):
        print(list[i][j],end=" ")
    print()

Upvotes: 0

Lokesh Senthilkumar
Lokesh Senthilkumar

Reputation: 97

r = int(input("Enter the number of rows in a matrix"))

c = int(input("Enter the number of columns in a matrix")) 

a = [list(map(int,input().split())) for _ in range(r)]

for i in a:
    print(*i)

Upvotes: 0

Sanjay Rai
Sanjay Rai

Reputation: 27

r = int(input("Enter Number of Rows : "))

c = int(input("Enter Number of Cols : "))

a = []

for i in range(r):

    b = []

    for j in range(c):
        j = int(input("Enter Number in pocket [" + str(i) + "][" + str(j) + "]"))
        b.append(j)
    a.append(b)
print("Matrix is ......")

for i in range(r):

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

    print()

Upvotes: 0

Yogesh Bisht
Yogesh Bisht

Reputation: 1

import numpy as np

#Taking the number of rows and columns from user

n=int(input("Enter the number of Rows\n"))
m=int(input("Enter the number of Columns\n"))

"""
 You can either use this loop method for below list comprehension;

a=[]
for i in range(n):
    a.append([0] * m )
"""

#Creating a Empty matrix as as per the instruction of user;

a = [ [0] * m for i in range(n) ]


#Taking the element for a matrix from user;

for i in range (n):
    for j in range(m):
        print("Enter Element No:",i,j)
        a[i][j] = int(input())

print(np.matrix(a))

Upvotes: 0

Aman
Aman

Reputation: 131

    #program to print matirx by row and column input

a,b = map(int,input("Enter row and column of matrix separated by a space ").split())

# empty list for matrix 
m=[] 

# taking matrix input
for i in range(1,a+1):
    l=[]
    for j in range(1,b+1):
        n=int(input(f"Enter a[{i}][{j}] element "))
        l.append(n)

    m.append(l)

#printing in matrix form
for i in range(a):
    for j in range(b):
        if(j==b-1):
            print(m[i][j], end="")
        else:
            print(m[i][j], end=" ")
    if i!=a-1:
        print()

Upvotes: 1

Mahesh Boopathi
Mahesh Boopathi

Reputation: 141

print"ENter r and c"

r = int(input("Enter the number of rows in a matrix"))

c = int(input("Enter the number of columns in a matrix"))

a = [[int(input()) for x in range (c)] for y in range(r)]

Upvotes: 0

Asher Mancinelli
Asher Mancinelli

Reputation: 304

This example from a program I use for calculating bigger matrices:

matrix = []
rows = int(input("Num rows: "))
cols = int(input("Num columns: "))
for r in range(rows):
    row = []
    for c in range(cols):
    row.append(int(input("M1-> R: {} C: {}\n>>>".format(r+1, c+1))))
    matrix.append(row)
print(matrix)

This will work for non-square matrices as well. I also use Sympy for doing matrix calculations, but that's besides the point:)

Upvotes: 0

Dave Rosenman
Dave Rosenman

Reputation: 1467

If you use pandas, and make a dataframe... if you enter 4 for the number of rows, and the numbers 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16... the script below

import pandas as pd
n = int(input("Enter the number of rows in a matrix: "))
a = [[0] * n for i in range(n)]
col_names = []
row_names = []


for i in range(n):
    col_names.append('col ' + str(i+1))
    row_names.append('row ' + str(i+1))  
    for j in range(n):
          a[i][j] = int(input())

print(pd.DataFrame(a,columns = col_names, index = row_names))

...will produce the following output.

       col 1  col 2  col 3  col 4
row 1      1      2      3      4
row 2      5      6      7      8
row 3      9     10     11     12
row 4     13     14     15     16

Another option... using numpy... and the same values from the first option...

import numpy as np
n = int(input("Enter the number of rows in a matrix: "))
a = [[0] * n for i in range(n)]



for i in range(n):
   for j in range(n):
        a[i][j] = int(input())

print(np.matrix(a))

...would produce

[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]
 [13 14 15 16]]

Upvotes: 1

Related Questions