[python] How to input matrix (2D list) in Python?

I tried to create this code to input an m by n matrix. I intended to input [[1,2,3],[4,5,6]] but the code yields [[4,5,6],[4,5,6]. Same things happen when I input other m by n matrix, the code yields an m by n matrix whose rows are identical.

Perhaps you can help me to find what is wrong with my code.

m = int(input('number of rows, m = '))
n = int(input('number of columns, n = '))
matrix = []; columns = []
# initialize the number of rows
for i in range(0,m):
  matrix += [0]
# initialize the number of columns
for j in range (0,n):
  columns += [0]
# initialize the matrix
for i in range (0,m):
  matrix[i] = columns
for i in range (0,m):
  for j in range (0,n):
    print ('entry in row: ',i+1,' column: ',j+1)
    matrix[i][j] = int(input())
print (matrix)

This question is related to python list input matrix

The answer is


This code takes number of row and column from user then takes elements and displays as a matrix.

m = int(input('number of rows, m : '))
n = int(input('number of columns, n : '))
a=[]
for i in range(1,m+1):
  b = []
  print("{0} Row".format(i))
  for j in range(1,n+1):
    b.append(int(input("{0} Column: " .format(j))))
  a.append(b)
print(a)

If you want to take n lines of input where each line contains m space separated integers like:

1 2 3
4 5 6 
7 8 9 

Then you can use:

a=[] // declaration 
for i in range(0,n):   //where n is the no. of lines you want 
 a.append([int(j) for j in input().split()])  // for taking m space separated integers as input

Then print whatever you want like for the above input:

print(a[1][1]) 

O/P would be 5 for 0 based indexing


I used numpy library and it works fine for me. Its just a single line and easy to understand. The input needs to be in a single size separated by space and the reshape converts the list into shape you want. Here (2,2) resizes the list of 4 elements into 2*2 matrix. Be careful in giving equal number of elements in the input corresponding to the dimension of the matrix.

import numpy as np
a=np.array(list(map(int,input().strip().split(' ')))).reshape(2,2)

print(a)

Input

array([[1, 2],
       [3, 4]])

Output


you can accept a 2D list in python this way ...

simply

arr2d = [[j for j in input().strip()] for i in range(n)] 
# n is no of rows


for characters

n = int(input().strip())
m = int(input().strip())
a = [[0]*n for _ in range(m)]
for i in range(n):
    a[i] = list(input().strip())
print(a)

or

n = int(input().strip())
n = int(input().strip())
a = []
for i in range(n):
    a[i].append(list(input().strip()))
print(a)

for numbers

n = int(input().strip())
m = int(input().strip())
a = [[0]*n for _ in range(m)]
for i in range(n):
    a[i] = [int(j) for j in input().strip().split(" ")]
print(a)

where n is no of elements in columns while m is no of elements in a row.

In pythonic way, this will create a list of list


m,n=map(int,input().split()) # m - number of rows; n - number of columns;

matrix = [[int(j) for j in input().split()[:n]] for i in range(m)]

for i in matrix:print(i)


no_of_rows = 3  # For n by n, and even works for n by m but just give no of rows
matrix = [[int(j) for j in input().split()] for i in range(n)]
print(matrix)

row=list(map(int,input().split())) #input no. of row and column
b=[]
for i in range(0,row[0]):
    print('value of i: ',i)
    a=list(map(int,input().split()))
    print(a)
    b.append(a)
print(b)
print(row)

Output:

2 3

value of i:0
1 2 4 5
[1, 2, 4, 5]
value of i:  1
2 4 5 6
[2, 4, 5, 6]
[[1, 2, 4, 5], [2, 4, 5, 6]]
[2, 3]

Note: this code in case of control.it only control no. Of rows but we can enter any number of column we want i.e row[0]=2 so be careful. This is not the code where you can control no of columns.


Apart from the accepted answer, you can also initialise your rows in the following manner - matrix[i] = [0]*n

Therefore, the following piece of code will work -

m = int(input('number of rows, m = '))
n = int(input('number of columns, n = '))
matrix = []
# initialize the number of rows
for i in range(0,m):
    matrix += [0]
# initialize the matrix
for i in range (0,m):
    matrix[i] = [0]*n
for i in range (0,m):
    for j in range (0,n):
        print ('entry in row: ',i+1,' column: ',j+1)
        matrix[i][j] = int(input())
print (matrix)

Creating matrix with prepopulated numbers can be done with list comprehension. It may be hard to read but it gets job done:

rows = int(input('Number of rows: '))
cols = int(input('Number of columns: '))
matrix = [[i + cols * j for i in range(1, cols + 1)] for j in range(rows)]

with 2 rows and 3 columns matrix will be [[1, 2, 3], [4, 5, 6]], with 3 rows and 2 columns matrix will be [[1, 2], [3, 4], [5, 6]] etc.


You can make any dimension of list

list=[]
n= int(input())
for i in range(0,n) :
    #num = input()
    list.append(input().split())
print(list)

output:

code in shown with output


a,b=[],[]
n=int(input("Provide me size of squre matrix row==column : "))
for i in range(n):
   for j in range(n):
      b.append(int(input()))
    a.append(b)
    print("Here your {} column {}".format(i+1,a))
    b=[]
for m in range(n):
    print(a[m])

works perfectly


rows, columns = list(map(int,input().split())) #input no. of row and column
b=[]
for i in range(rows):
    a=list(map(int,input().split()))
    b.append(a)
print(b)

input

2 3
1 2 3
4 5 6

output [[1, 2, 3], [4, 5, 6]]


If your matrix is given in row manner like below, where size is s*s here s=5 5 31 100 65 12 18 10 13 47 157 6 100 113 174 11 33 88 124 41 20 140 99 32 111 41 20

then you can use this

s=int(input())
b=list(map(int,input().split()))
arr=[[b[j+s*i] for j in range(s)]for i in range(s)]

your matrix will be 'arr'


a = []
b = []

m=input("enter no of rows: ")
n=input("enter no of coloumns: ")

for i in range(n):
     a = []
     for j in range(m):
         a.append(input())
     b.append(a)

Input : 1 2 3 4 5 6 7 8 9

Output : [ ['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9'] ]


If the input is formatted like this,

1 2 3
4 5 6
7 8 9

a one liner can be used

mat = [list(map(int,input().split())) for i in range(row)]

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to list

Convert List to Pandas Dataframe Column Python find elements in one list that are not in the other Sorting a list with stream.sorted() in Java Python Loop: List Index Out of Range How to combine two lists in R How do I multiply each element in a list by a number? Save a list to a .txt file The most efficient way to remove first N elements in a list? TypeError: list indices must be integers or slices, not str Parse JSON String into List<string>

Examples related to input

Angular 4 - get input value React - clearing an input value after form submit Min and max value of input in angular4 application Disable Button in Angular 2 Angular2 - Input Field To Accept Only Numbers How to validate white spaces/empty spaces? [Angular 2] Can't bind to 'ngModel' since it isn't a known property of 'input' Mask for an Input to allow phone numbers? File upload from <input type="file"> Why does the html input with type "number" allow the letter 'e' to be entered in the field?

Examples related to matrix

How to get element-wise matrix multiplication (Hadamard product) in numpy? How can I plot a confusion matrix? Error: stray '\240' in program What does the error "arguments imply differing number of rows: x, y" mean? How to input matrix (2D list) in Python? Difference between numpy.array shape (R, 1) and (R,) Counting the number of non-NaN elements in a numpy ndarray in Python Inverse of a matrix using numpy How to create an empty matrix in R? numpy matrix vector multiplication