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
  • why not using numpy? Commented Oct 10, 2016 at 12:16
  • 3
    I wanted to do without numpy Commented Oct 10, 2016 at 12:19

2 Answers 2

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]]
Sign up to request clarification or add additional context in comments.

4 Comments

@FrancescoRastelli Check the example.
@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.
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. :)
@Jérôme: Please take a look at Python list of lists, changes reflected across sublists unexpectedly and let me know if you still have questions on this topic.
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]]

3 Comments

That's 3 rows x 2 columns. The OP wants 2 rows x 3 columns.
@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 ...
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.