I’m trying to update values in a list of lists using the following source code:
target_agreement = get_object_or_404(TargetAgreement.objects, pk=agreement_id)
target_category_set = TargetCategory.objects.filter(company=target_agreement.company, is_active=True).order_by('position')
category_targets = []
if target_category_set:
totals = [[0]*3]*len(target_category_set) #list of lists with list on level 2 having length of 3
else:
totals = [[0]*3]*1
for (index1,target_category) in enumerate(target_category_set):
category_targets_temp = []
for (index2,target) in enumerate(target_category.category_targets.filter(user=request.user, agreement=target_agreement)):
category_targets_temp.append(target)
print "*******"
print "index is: "
print index1
print totals[index1][0]
totals[index1][0] = totals[index1][0] + target.weight
print totals[index1][0]
print "totals are"
print totals
print "*******"
print "final result"
print totals[index1][0]
print totals
print "-----"
category_targets.append(category_targets_temp)
print totals
The behavior I do not understand is that totals[index1][0] = totals[index1][0] + target.weight is not only updating the first element in the list referenced by index1, but all first elements in all lists.
The result is like the following:
[[88, 0, 0], [88, 0, 0], [88, 0, 0], [88, 0, 0]]
But I would have expected:
[[36, 0, 0], [50, 0, 0], [1, 0, 0], [1, 0, 0]]
Can somebody clarify what I did wrong. Thanks for your help.
The reason is the way you created that
totalslist. By multiplying the list –You create a list whose elements are references to the same list. Thus, when you modify one element, all of them are modified. Consider:
But you could avoid this by changing the list definition: