Just ziplists to create pairs, multiply them and feed in sum:
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> sum(x * y for x, y in zip(a, b))
32
The above zipwill return an iterable tuple set containing one number from both lists:
>>> list(zip(a, b))
[(1, 4), (2, 5), (3, 6)]
Then the generator expression is used to multiply the numbers together:
>>> list(x*y for x, y in list(zip(a, b)))
[4, 10, 18]
Finally, sumused to sum them for the final result:
>>> sum(x*y for x, y in list(zip(a, b)))
32
source
share