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