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:

JavaScript

output:

JavaScript

expected output:

JavaScript

Advertisement

Answer

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

JavaScript

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

JavaScript

Then generator expression is used to multiply the numbers together:

JavaScript

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

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement