I have list of 10 elements having a tuple of 2 elements I want to add to each tuple a value but when i write the following code to do so it seems that cumulative sum is caluculated . How is this happening. please help
# -*- coding: utf-8 -*-
i=0
k=10
count=[]
value=[1,2]
while i < k:
count.append(value)
i=i+1
t=[10,2]
i=0
#for item in count:
#print item
while i <(len(count)):
count[i][0]+=t[0];
count[i][1]+=t[1];
i+=1;
for item in count:
print item
outpus is coming out to be
[101, 22]
[101, 22]
[101, 22]
[101, 22]
[101, 22]
[101, 22]
[101, 22]
[101, 22]
[101, 22]
[101, 22]
where as i expected it to be
[11, 4]
[11, 4]
[11, 4]
[11, 4]
[11, 4]
[11, 4]
[11, 4]
[11, 4]
[11, 4]
[11, 4]
That’s because you actually have a list of ten references to the same (single) 2-item list. You are repeatedly adding to that same list in the second loop. You really want a new instance of a the sublist (and what you really have is a mutable list, not a tuple).
You could do this:
To get new copies of the embedded list.