0

I have a very long list of integers my_list, together with an equivalence relation ~ on the set of indices. I need to define a new list new_list with the same set of indices by (in pseudocode)

new_list[i] = sum over all j with j~i of my_list[j]

Since this is a very long list, to save time I wanted to do the following. First, break the collection of indices I into equivalence classes I/~, and then for each equivalence class C write

for i in C:
    new_list[i] = C_sum
    C_sum += my_list[i]

The hope was that for each i I could define new_list[i] to POINT to the variable C_sum, and then when I modify C_sum in the for loop, new_list[i] would still point to C_sum which would now be larger. But this didn't work. I thought that a) lists store references to objects, and that b) the += command modified the existing value rather than re-binding the variable to a new value. Where did I go wrong, and is there a way I can accomplish something like what I wanted -- namely, defining new_list on a single equivalence class inside just one loop?

Twiffy
  • 425
  • 1
  • 4
  • 10
  • 3
    Briefly: yes, the list is mutable. However, the integers it holds are not. You can wrap each integer in its own list, but you probably have an [XY Problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – TigerhawkT3 Apr 13 '17 at 00:00
  • Thanks, that solves the first part of my question. I suppose += is only an "in-place" modification for mutable data types. – Twiffy Apr 13 '17 at 00:05
  • @TigerhawkT3 I disagree that my question is a duplicate of the post you linked, as that post doesn't address the second (and much more important) part of my question. – Twiffy Apr 13 '17 at 00:05

0 Answers0