Very simple code nested example:
All the code does is create a list of lists that is initialized to zero.
It iterates through the list rows and columns and each position is given a value.
For some reason the last row of the 2D list is duplicated for each row when the final vector is printed.
Number_of_channels=2
Coefficients_per_channel=3
coefficient_array=[[0]*Coefficients_per_channel]*Number_of_channels
print coefficient_array
for channel in range(Number_of_channels):
for coeff in range(Coefficients_per_channel):
coefficient_array[channel][coeff]=coeff*channel
print coefficient_array[channel][coeff]
print coefficient_array
Output:
[[0, 0, 0], [0, 0, 0]]
0
0
0
0
1
2
[[0, 1, 2], [0, 1, 2]]
I actually expect:
[[0, 0, 0], [0, 1, 2]]
Anyone have any idea how come this is happening?
You only duplicate the outer list, but the values of that list are left untouched. Thus, all (both) outer lists contain references to the same inner, mutable list.
Better create the inner lists in a loop:
or, illustrated with the python prompt again: