Possible Duplicate:
Python : how to append new elements in a list of list?
I came up with this very strange (for me) behaviour in Python.
I have an empty 2D list (or array if you prefer), and when I add an element to one of it’s columns, all the other columns get the same value added.
Here is the code:
row = [1, 2, 3, 4]
yChannel = 4*[[]]
sectorPlace = 0
for sector in yChannel:
sector.append(row[sectorPlace])
sectorPlace += 1
print yChannel
And the output:
[[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]
The line
creates a list with four times the same list object. Modifying this single list object will seemingly modify all for sublists, since they are actually all the same list object. You should use
to create a list of four independent sublists.