Matrix basic help in python

Question:

n=input("r")
m=input("c")
l=range(m*n)
for r in range(m):
    for c in range(n):
        l[r][c]=input(" enter no")
for r in range(m):
    for c in range(n):
        print[r][c]
    print

i thought of practicing matrix questions but when i ran my matrix coding in python it gave an error

Traceback (most recent call last):
  File "D:/WORK/Python 2.7/matrix1", line 6, in <module>
    l[r][c]=input(" enter no")
TypeError: 'int' object does not support item assignment

i m new and a student please help explain simply please i really need to understand it

Asked By: R2076

||

Answers:

To create a 2D matrix replace:

l=range(m*n)

by:

l=[[0 for i in range(m)] for j in range(n)]  

Demo:

>>> n=4
>>> m=3
>>> l=[[0 for i in range(m)] for j in range(n)]  # you can use any value instead of 0 to initialize matrix
>>> l
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
Answered By: Irshad Bhat
n=input("r")
m=input("c")
myMatrix = [[0 for col in xrange(m)] for row in xrange(n)]
for row in xrange(n):
    for col in xrange(m):
        myMatrix[row][col] = input("enter no: ")

Now, to look at the matrix:

for row in myMatrix:
    for num in row:
        print num,
    print ""

Your problem comes from the fact that range(m*n) returns a flat list, when what you want is a list of sublists (where each sublist is a row in the matrix)

Answered By: inspectorG4dget

For create matrix I advise you to use numpy

An example here example

With l=range(m*n) you create a list, not a 2D matrix.

Answered By: Tiket_dev
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.