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)
Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
Multiply Two Lists in Python Using the numpy. multiply() Method. The multiply() method of the NumPy library in Python, takes two arrays/lists as input and returns an array/list after performing element-wise multiplication.
sum() function in Python Python provides an inbuilt function sum() which sums up the numbers in the list. Syntax: sum(iterable, start) iterable : iterable can be anything list , tuples or dictionaries , but most importantly it should be numbers.
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
You have some problems in your code, first off you cant index your list with parenthesis you need []
, secondly you've created a generator not a number.
You need to zip
your lists first:
In [3]: sum(i*j for i,j in zip(a, b))
Out[3]: 32
Or as a functional approach use operator.mul
within map
and sum
:
In [11]: from operator import mul
In [12]: sum(map(mul, a, b))
Out[12]: 32
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With