This really, really messed with me today. This is the most minimum working example I could get:
array = [ 1, 2, 1, 3, 4 ]
n = 3
strips = [[0] * n] * n
mSum = 7
j = 0
strips[0][j] = mSum
print(f'before strips[0]: {strips[0][0]}')
for i in range(1, len(array) - n + 1):
mSum += array[i + n - 1] - array[i - 1]
strips[i][j] = mSum
print(f'strips[{i}][{j}]: {strips[i][j]}')
print(f'after strips[0]: {strips[0][0]}')
If strips is not a nested-list, the error doesn't occur. Here is the output:
before strips[0][0]: 7
strips[1][0]: 9
strips[2][0]: 11
after strips[0][0]: 11
Why is strips[0][0] different before and after the loop (where it does not get modified)? The only thing I can think of is that it's somehow connected to mSum.
The same code in a language like C++ does not have this issue.
From Common Sequence Operations, s * n is equivalent to adding s to itself n times. You created a list with
nzeros in it, then added that list to an outer listntimes. Now you have a bunch of references to a single list.Python's
listwould be like a C++std::list, not something likeint test[10][10];.In your case, you are doing the equivalent of
that
tmplist wouldn't have any idea how its values were created so it wouldn't have any ability to create new ones. Instead it just duplicates.You can get what you want with
This still has the problem where
[0] * njust adds new references to0to fill the array. This is not a problem for any immutable type because, well, they can't be changed, so who cares if there are a bunch of references to them. It would be a problem if you were using some other mutable type.