0

I am trying to do something quite trivial and am getting very strange behaviour. First i created a list like this:

sums = [[0, 0, 0]] * n

where n is any number. next i have a loop that filters out tuples in a numpy array that have a -1 in one of their fields and adds numbers from the tuples to elements of the nested lists like so:

for i in data_tuples:
        if i[6] == -1:
            continue
        counts[i[6]] += 1
        sums[i[6]][0] = sums[i[6]][0] + i[3]
        sums[i[6]][1] = sums[i[6]][1] + i[4]
        sums[i[6]][2] = sums[i[6]][2] + i[5]

the problem is that the addition operation is performed on every sublist in the sums list. for example adding 3, 2 and 5 to the list in the way above gives [[3, 2, 5], [3, 2, 5]] and adding 2, 2, 4 after that gives [[5, 4, 9], [5, 4, 9]]. This happens when i only update one of the nested lists in the sums list. Any ideas? (i[6] is simply an index into the sums list)

1 Answers1

0

It's because of reference model. You can use this site to understand why your code is not working correctly. To fix your code, you should write list-comprehension:

sums = [[0, 0, 0] for _ in range(n)]
minmon
  • 18
  • 5