Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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)
like image 463
Ravy Avatar asked Jan 24 '17 06:01

Ravy


People also ask

How do you find the sum of two elements in a list in Python?

Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].

Can you multiply 2 lists in Python?

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.

How do you sum a list of items in Python?

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.


2 Answers

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
like image 157
niemmi Avatar answered Oct 08 '22 18:10

niemmi


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
like image 29
Mazdak Avatar answered Oct 08 '22 19:10

Mazdak