I am new to Python 3.4 and I usually use MATLAB/ GNU Octave for matrix calculation. I know we can perform matrix calculation using numpy in Python 2.x, but numpy does not work for Python 3.4.
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)
Creating matrix with prepopulated numbers can be done with list comprehension. It may be hard to read but it gets job done:
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.
The problem is on the initialization step.
This code actually makes every row of your
matrix
refer to the samecolumns
object. If any item in any column changes - every other column will change:You can initialize your matrix in a nested loop, like this:
or, in a one-liner by using list comprehension:
or:
See also:
Hope that helps.
you can accept a 2D list in python this way ...
simply
for characters
or
for numbers
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
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 -
Input : 1 2 3 4 5 6 7 8 9
Output : [ ['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9'] ]
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)