Hello there
I'm reading How to think like a computer scientist which is an introductory text for "Python Programming".
I want to clarify the behaviour of multiply operator (*
) when applied to lists.
Consider the function make_matrix
def make_matrix(rows, columns):
"""
>>> make_matrix(4, 2)
[[0, 0], [0, 0], [0, 0], [0, 0]]
>>> m = make_matrix(4, 2)
>>> m[1][1] = 7
>>> m
[[0, 0], [0, 7], [0, 0], [0, 0]]
"""
return [[0] * columns] * rows
The actual output is
[[0, 7], [0, 7], [0, 7], [0, 7]]
The correct version of make_matrix is :
def make_matrix(rows, columns):
"""
>>> make_matrix(3, 5)
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
>>> make_matrix(4, 2)
[[0, 0], [0, 0], [0, 0], [0, 0]]
>>> m = make_matrix(4, 2)
>>> m[1][1] = 7
>>> m
[[0, 0], [0, 7], [0, 0], [0, 0]]
"""
matrix = []
for row in range(rows):
matrix += [[0] * columns]
return matrix
The reason why first version of make_matrix fails ( as explained in the book at 9.8 ) is that
...each row is an alias of the other rows...
I wonder why
[[0] * columns] * rows
causes ...each row is an alias of the other rows...
but not
[[0] * columns]
i.e. why each [0]
in a row is not an alias of other row element.