A Python Oddity
The Oddity
Let’s say you want to intialize a matrix (a two-dimensional list) in python. It’ll be an NxN matrix of numbers. Just for fun we’ll make all the inital elements 1, instead of 0.
One might think the following would be a sensible one-liner.
# sample.py
def print_mat(matrix):
for row in matrix:
print(row)
matrix = [[1] * 10] * 10
print_mat(matrix)
prints
$ python3 sample.py
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
But, what happens if we modify part of the matrix?