I recently stumbled on some serious weirdness with python lists if you try to use them like arrays (not by appending):
make a list by duplication:
myLists = 5 * [3 * [0]]
print(myLists)
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
run this...you get:
for i in range(5):
for j in range(3):
myLists[i][j] = i + j
print(myLists)
[[4, 5, 6], [4, 5, 6], [4, 5, 6], [4, 5, 6], [4, 5, 6]]
why only the last row copied everywhere?
now, create the list contiguously with list comprehension:
myLists = [[0 for i in range(3)] for j in range(5)]
print(myLists)
here it is (it's the same structure):
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
run the same loops...now you get:
for i in range(5):
for j in range(3):
myLists[i][j] = i + j
print(myLists)
[[0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6]]
now it's correct...
I'm guessing some strange linked-list-related pointer details under the CPython hood cause this, but I don't know what they are...
Can anyone help?