cabeggar

Python Matrix Assignment

It’s convenient to construct a matrix in Python using multiplication:

1
2
3
>>> mat = [[0] * 5] * 5
>>> mat
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]

However, we can meet some problems when we want to modify only one element.

1
2
3
>>> mat[0][0] = 1
>>> mat
[[1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0]]

We can found that by modifying only one element of the matrix, we modify the whole column. The reason is python use reference for lists, and by the first line code, we created 5 duplicate reference to the same row. When we try to modify only one row, we are modifying all the rows referred by the same reference.

A better solution is to create matrix in this way:

1
2
3
4
5
6
>>> mat = [[0] * 5 for _ in xrange(5)]
>>> mat
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
>>> mat[0][0] = 1
>>> mat
[[1, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]