I want to sum the products of all distinct pairs in a list. I wrote the following code that counts correctly this: 1*2 + 1*3 + 1*4 + 2*3 + 2*4 + 3*4
l = [1, 2, 3, 4]
def sum_of_pairs(ls):
return sum([x * y for x in ls for y in ls[ls.index(x) + 1:]])
print(sum_of_pairs(l))
When I try to change list to l = [1, 1, 1, 1] it returns 12 (and not 6).
Why is this happening?