In python I came across this strange phenomena while working with itertools groupby module.
In python, variable assignment means assigning the new variable its own memory instead of a pointer to the original memory (from my understanding if this is incorrect please let me know):
y = 7
x = y
y = 9
x will still be 7
Yet when I was working with groupby module, I was using this module to group items that had the same key into one group. I wanted two groups since reiterating over the original group was useless as the memory would have already been modified. Example:
for key, group in groupby(rows, lambda x: x[0]):
data = [thing[1] for thing in group] #accesses 1st attribute of element
data2 = [thing[2] for thing in group] # would yield [] as group is empty
So I tried this instead:
for key, group in groupby(rows, lambda x: x[0]):
#create a copy of group to reiterate over
toup = group
print toup #<itertools._grouper object at 0x1039a8850>
print group #<itertools._grouper object at 0x1039a8850>
data = [thing[1] for thing in group] #accesses 1st attribute of element
data2 = [thing[2] for thing in toup]
data2 should access the 2nd item but yields [] since they both share the same memory
My question is why does this happen? Shouldn't assigning group to toup means toup would have a copy of groups memory at a different hex address location?
Also what can I do to circumvent this problem so I don't have to write two groupby iterations?