Python list manipulation differs based on initialization
Question:
I want to have square matrix of integers with dimensions 3×3. I don’t want to use numpy. There are several ways how to initialize such structure. For example:
Direct definition (explicitly written out the whole structure):
a = [ [0,0,0], [0,0,0], [0,0,0] ]
and
b = [[0]*3]*3
When I type ‘a’ or ‘b’ in python3 interpreter I got same results (str
function for both objects prints out the same):
>>> a
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> b
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
however, when I try to set for example number on position row, column = 0, 1 I get different results:
>>> a[0][1] = 1
>>> b[0][1] = 1
>>> a
[[0, 1, 0], [0, 0, 0], [0, 0, 0]]
>>> b
[[0, 1, 0], [0, 1, 0], [0, 1, 0]]
How so? What’s special about [[0]*3]*3
?
Answers:
The second one creates three rows that are addressing the same memory. This way any change in one of them reflects to them all. The first one, on the other side, creates three separate lists
I want to have square matrix of integers with dimensions 3×3. I don’t want to use numpy. There are several ways how to initialize such structure. For example:
Direct definition (explicitly written out the whole structure):
a = [ [0,0,0], [0,0,0], [0,0,0] ]
and
b = [[0]*3]*3
When I type ‘a’ or ‘b’ in python3 interpreter I got same results (str
function for both objects prints out the same):
>>> a
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> b
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
however, when I try to set for example number on position row, column = 0, 1 I get different results:
>>> a[0][1] = 1
>>> b[0][1] = 1
>>> a
[[0, 1, 0], [0, 0, 0], [0, 0, 0]]
>>> b
[[0, 1, 0], [0, 1, 0], [0, 1, 0]]
How so? What’s special about [[0]*3]*3
?
The second one creates three rows that are addressing the same memory. This way any change in one of them reflects to them all. The first one, on the other side, creates three separate lists