How can I multiply every element in a list with every other element in the list by using a for loop? Like this: [1, 3, 5, 7] should be multiplied like this: 1 * 3 1 * 5 1 * 7 3 * 5 3 * 7 5 * 7
CodePudding user response:
Sure you can:
a = [1, 3, 5, 7]
s = 0
for i in range(len(a)):
for j in range(i 1, len(a)):
s = a[i] * a[j]
print(s)
CodePudding user response:
You can multiply together each combination generated by combinations
and sum them.
from itertools import combinations
from operator import mul
l = [1, 3, 5, 7]
sum([mul(*x) for x in combinations(l,2)])
Output
86
CodePudding user response:
Use 2 loops to get the combinations of the list elements. Multiply the list elements then add them.
l = [1, 3, 5, 7]
sum = 0
for i in range(len(l)):
for j in range(i 1, len(l)):
sum = l[i]*l[j]