0

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

3 Answers3

1

Without usage of list indexes:

listit = [1, 5, 3, 7]

x_position = 0
result = 0

for x in listit:
    x_position += 1
    y_position = 0
    for y in listit:
        y_position += 1
        if x_position < y_position:
            print(f"{x} * {y}")
            result += x * y
            print(result)

print(result)
RomanG
  • 230
  • 1
  • 8
0

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)
Yevgeniy Kosmak
  • 3,561
  • 2
  • 10
  • 26
0

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
Chris
  • 15,819
  • 3
  • 24
  • 37