How to input matrix (2D list) in Python?

The problem is on the initialization step.

for i in range (0,m):
  matrix[i] = columns

This code actually makes every row of your matrix refer to the same columns object. If any item in any column changes – every other column will change:

>>> for i in range (0,m):
...     matrix[i] = columns
... 
>>> matrix
[[0, 0, 0], [0, 0, 0]]
>>> matrix[1][1] = 2
>>> matrix
[[0, 2, 0], [0, 2, 0]]

You can initialize your matrix in a nested loop, like this:

matrix = []
for i in range(0,m):
    matrix.append([])
    for j in range(0,n):
        matrix[i].append(0)

or, in a one-liner by using list comprehension:

matrix = [[0 for j in range(n)] for i in range(m)]

or:

matrix = [x[:] for x in [[0]*n]*m]

See also:

Hope that helps.

Leave a Comment