Python matrix input not working this way?

Question:

I have tried several ways that are working. But, this one is not.
Please help me understand why ?

row, col = 2, 3
mat1 = [[None]*col]*row
print(mat1)
for i in range(0, row):
    for j in range(0, col):
        mat1[i][j] = int(input())
print(mat1)

Input:

1
2
3
4
5
6

Expected:

[[1,2,3], [4,5,6]]

Getting:

[[4,5,6], [4,5,6]]
Asked By: randomname

||

Answers:

This worked for me. I tested it on Google Colab:

row, col = 2, 3
mat1 = [[None for _ in range(col)] for _ in range(row)]
print(mat1)
for i in range(row):
    for j in range(col):
        mat1[i][j] = int(input())
print(mat1)
Answered By: cconsta1

The problem is in line 2 when you create your matrix mat1 with the * operator.

The two lots of [[None]*col] defined by [[None]*3]*2 are referencing the same list in memory – this is why modifying your second list (unexpectedly) results in the first list being modified as well.

Another example:

>>> a = [[1, 2]*2]*3
>>> a
[[1, 2, 1, 2], [1, 2, 1, 2], [1, 2, 1, 2]]

>>> a[0][2] = 3
>>> a[0][3] = 4
>>> a
[[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]

As you can see, changing a[0] led to the other two lists being changed as well.

As other answers have pointed out, this can be resolved with a list comprehension:

mat1 = [[None for _ in range(col)] for _ in range(row)]
Answered By: Portly1418
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.