2

I have this matrix:

mat = [[ 0 for x in range(row)] for y in range(column)]

I tried to add elements to the matrix:

for x in range(row): # row is 2 
    for y in range(column): # column is 3
        mat[x][y] = int(input("number: "))

but the shell returns this error:

Traceback (most recent call last):
File "C:\Users\Fr\Desktop\pr.py", line 13, in <module>
mat[x][y] = 12
IndexError: list assignment index out of range

how do I add elements to a matrix?

2 Answers2

4

The inner list should be based on columns:

mat = [[ 0 for x in range(column)] for y in range(row)]

Here is an example:

In [73]: row = 3
In [74]: column = 4
In [78]: mat = [[ 0 for x in range(column)] for y in range(row)]

In [79]: 

In [79]: for x in range(row): # row is 2 
             for y in range(column): # column is 3
                 mat[x][y] = 5
   ....:         

In [80]: mat
Out[80]: [[5, 5, 5, 5], [5, 5, 5, 5], [5, 5, 5, 5]]
Mazdak
  • 105,000
  • 18
  • 159
  • 188
  • @FrancescoRastelli Check the example. – Mazdak Oct 10 '16 at 12:29
  • @FrancescoRastelli: In that case, something strange is going on, or you misunderstood Kasra's answer. Please add the _complete_ code that you tried to the end of your question. – PM 2Ring Oct 10 '16 at 12:31
  • FWIW, it's safe to do `mat = [[0]*column for y in range(row)]`; it's also a bit faster & more compact. OTOH, I guess doing it the long way is easier that explaining why `[[0]*column]*row` is _not_ safe. :) – PM 2Ring Oct 10 '16 at 12:34
  • @Jérôme: Please take a look at [Python list of lists, changes reflected across sublists unexpectedly](http://stackoverflow.com/q/240178/4014959) and let me know if you still have questions on this topic. – PM 2Ring Oct 10 '16 at 12:45
1

I think it should be:

>>> for x in range(column):
...     for y in range(row):
...             mat[x][y] = int("number: ")
...
1
2
3
4
5
6
>>> mat
[[1, 2], [3, 4], [5, 6]]
coder
  • 12,832
  • 5
  • 39
  • 53
  • That's 3 rows x 2 columns. The OP wants 2 rows x 3 columns. – PM 2Ring Oct 10 '16 at 12:28
  • @PM2Ring, Yes but then the `mat` is considered falsely created. The matrix initially=empty is in this form: `[[0, 0], [0, 0], [0, 0]]` or at least that is what the OP creates ... – coder Oct 10 '16 at 12:30
  • And that's the cause of the OP's problem! According to their code comments, they _want_ a matrix with 2 rows x 3 columns, but they got their rows & columns transposed. – PM 2Ring Oct 10 '16 at 12:43