Skip to content
Advertisement

How can I sum the product of two list items using for loop in python?

I am trying to sum the product of two different list items in the same line using for loop, but I am not getting the output as expected.

My example code:

a = [1,2,3]
b = [4,5,6]

sum = 0              # optional element

score = ((sum+(a(i)*b(i)) for i in range(len(a)))

print score

output:

<generator object <genexpr> at 0x027284B8>

expected output:

32                   # 0+(1*4)+(2*5)+(3*6)

Advertisement

Answer

Just zip the lists to generate pairs, multiply them and feed to sum:

>>> a = [1,2,3]
>>> b = [4,5,6]
>>> sum(x * y for x, y in zip(a, b))
32

In above zip will return iterable of tuples containing one number from both lists:

>>> list(zip(a, b))
[(1, 4), (2, 5), (3, 6)]

Then generator expression is used to multiply the numbers together:

>>> list(x*y for x, y in list(zip(a, b)))
[4, 10, 18]

Finally sum is used to sum them together for final result:

>>> sum(x*y for x, y in list(zip(a, b)))
32
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement