-3
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

R2076
  • 54
  • 7
  • `l=range(m*n)` doesn't create a "matrix", just a list of integers, so `l[r]` is an `int` and you can't index into it with `c`. – jonrsharpe Jan 20 '15 at 15:12
  • 1
    `range(.)` will give you a 1 dimensional array, you try to access it as a 2D array. Example: `>>> range(5)` --> `[0, 1, 2, 3, 4]` – martijnn2008 Jan 20 '15 at 15:13
  • so how shold i edit the coding – R2076 Jan 20 '15 at 15:13
  • How to make a 2D array a.k.a. matrix, use Google and you will find: http://stackoverflow.com/questions/6667201/how-to-define-two-dimensional-array-in-python – martijnn2008 Jan 20 '15 at 15:15

3 Answers3

1
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)

inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
0

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]]
Irshad Bhat
  • 8,479
  • 1
  • 26
  • 36
0

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.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Tiket_dev
  • 141
  • 1
  • 11