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
Answer from niemmi on Stack Overflow
Discussions

sympy - Produce the sum of products over two lists with python? - Stack Overflow
As unutbu mentioned python already provide such a function in itertools.imap under python2 and the built'-in's map in python3, so you can avoid re-writing it and use either: ... Which of all options in two current answers might me more memory/cpu optimal? More on stackoverflow.com
🌐 stackoverflow.com
How do I sum product between a list and linear coefficient
You've gotten basic answers, so just to add - if you're going to do this sort of thing lot, I suggest looking into numpy. More on reddit.com
🌐 r/learnpython
9
2
March 18, 2022
Assignment 5-1 : Sum of Product - Make a function "sumProduct()" that receives two lists of integers and returns the sum of multiplying the corresponding list items Assumption: two lists must be the same length def sumproduct (11,12) : return sumP r result = sumproduct(list1, list2) main.py 1234 import random def sumoProduct (21,2): \# make your code
Answer to Assignment 5-1 : Sum of Product - Make a function More on chegg.com
🌐 chegg.com
1
November 19, 2022
Sumproduct iteratively

Oh, so many problems in one post ;)

At first you should check if you can convert the list entries into integers. The best use case is to ask for forgivness and use try-except. That means if int(something) raises an Error, catch that specific error and handle it:

>>> def check_for_ints(entry):
try:
return int(entry)
except ValueError:
return None


>>> check_for_ints("2")
2
>>> check_for_ints("")
>>> check_for_ints("jhkajshkljh")

See, this will only return something that can converted to an integer.

Noe, we're taking your input lists and we're creating two new lists, with proper integers:

>>> list1 = ['10', '9', '', '20', '30', '1']
>>> list2 = ['15', '2', '', '58', '0', '2']
>>> inter1 = [check_for_ints(i) for i in list1 if not check_for_ints(i) is None]
>>> inter2 = [check_for_ints(i) for i in list2 if not check_for_ints(i) is None]
>>> inter1
[10, 9, 20, 30, 1]
>>> inter2
[15, 2, 58, 0, 2]

Now, we have interger lists, let us build a list of products:

>>> product = [i*j for i, j in zip(inter1, inter2)]
>>> product
[150, 18, 1160, 0, 2]

Finally we only have to sum it up:

>>> sum(product)
1330

Or without the intermediate steps:

>>> sum(i*j for i, j in zip(
(check_for_ints(i) for i in list1 if not check_for_ints(i) is None),
(check_for_ints(i) for i in list2 if not check_for_ints(i) is None))
)
1330

I used list comprehensions here, a powerful tool and shortcut, if you have problems understanding them, read this very nice piece of documentation. Good luck!

More on reddit.com
🌐 r/learnpython
24
3
November 10, 2015
🌐
Stack Overflow
stackoverflow.com › questions › 69421685 › sum-of-products-of-two-lists
python - Sum of products of two lists - Stack Overflow
def avgdiff(mylist): listavg=sum(mylist)/len(mylist) outval=1 for x in mylist: outval=outval*abs(x-listavg) return outval x1 = [3,1,3,1,3,13] x2 = [2,3,31,3,13,3] print(avgdiff(x1)*avgdiff(x2))
🌐
Coderanch
coderanch.com › t › 755906 › languages › Sum-product-python
Sum product in python (Jython/Python forum at Coderanch)
Hi, From the below attachment I ... sum product and the answer need to be store in new Column called “result” Anyone help me with this please ? Thank you ... It looks like an Excel. Why do you need to write it in Python if you got your data in Excel sheet already? Can't you calculate using an existing supported formulae? ... hi Swin, and welcome to the Ranch! To get a sumproduct of two lists in python, ...
Top answer
1 of 2
3
In [159]: import sympy as sy

In [160]: from sympy.abc import x

In [161]: terms = [1, x, x*(x-1)]

In [162]: coefficients = [-1,8.1,7]

In [163]: sum(t*c for t, c in zip(terms, coefficients))
Out[163]: 7*x*(x - 1) + 8.1*x - 1

Interestingly, sum(term*coef for term, coef in zip(terms, coefficients)) is a bit faster than sum(coef * term for coef, term in zip(coefficients, terms)):

In [182]: %timeit sum(term * coef for term, coef in zip(terms, coefficients))
10000 loops, best of 3: 34.1 µs per loop

In [183]: %timeit sum(coef * term for coef, term in zip(coefficients, terms))
10000 loops, best of 3: 38.7 µs per loop

The reason for this is because coef * term calls coef.__mul__(term) which then has to call term.__rmul__(coef) since ints do not know how to multiply with sympy Symbols. That extra function call makes coef * term slower than term * coef. (term * coef calls term.__mul__(coef) directly.)

Here are some more microbenchmarks:

In [178]: %timeit sum(IT.imap(op.mul, coefficients, terms))
10000 loops, best of 3: 38 µs per loop

In [186]: %timeit sum(IT.imap(op.mul, terms, coefficients))
10000 loops, best of 3: 32.8 µs per loop

In [179]: %timeit sum(map(op.mul, coefficients, terms))
10000 loops, best of 3: 38.5 µs per loop

In [188]: %timeit sum(map(op.mul, terms, coefficients))
10000 loops, best of 3: 33.3 µs per loop

Notice that the order of the terms and coefficients matters, but otherwise there is little time difference between these variants. For larger input, they also perform about the same:

In [203]: terms = [1, x, x*(x-1)] * 100000

In [204]: coefficients = [-1,8.1,7] * 100000

In [205]: %timeit sum(IT.imap(op.mul, terms, coefficients))
1 loops, best of 3: 3.63 s per loop

In [206]: %timeit sum(term * coef for term, coef in zip(terms, coefficients))
1 loops, best of 3: 3.63 s per loop

In [207]: %timeit sum(map(op.mul, terms, coefficients))
1 loops, best of 3: 3.48 s per loop

Also be aware that if you do not know (through profiling) that this operation is a critical bottleneck in your code, worrying about these slight differences is a waste of your time, since the time it takes to pre-optimize this stuff is far greater than the amount of time you save whilst the code is running. As they say, preoptimization is the root of all evil. I'm probably already guilty of that.


In Python2,

sum(IT.imap(op.mul, coefficients, terms))

uses the least memory.

In Python3, zip and map returns iterators, so

sum(t*c for t, c in zip(terms, coefficients))    
sum(map(op.mul, coefficients, terms))

would also be memory-efficient.

2 of 2
1

Using a simple generator expression:

sum(coef * term for coef, term in zip(coefficients, terms))

Alternatively, instead of using zip you want to use something similar to zip_with:

def zip_with(operation, *iterables):
    for elements in zip(*iterables):
        yield operation(*elements)

And use it as:

import operator as op

sum(zip_with(op.mul, coefficients, terms))

As unutbu mentioned python already provide such a function in itertools.imap under python2 and the built'-in's map in python3, so you can avoid re-writing it and use either:

sum(itertools.imap(op.mul, coefficients, terms))

or

sum(map(op.mul, coefficients, terms) #python3

python 2 map works slightly differently when you pass more than one sequence and the length differ.

🌐
Kentynhos
kentynhos.com › hyacinthoides-hispanica-fqyqkmi › python-sum-product-of-two-lists-589b70
python sum product of two lists
I want to perform an element wise multiplication, to multiply two lists together by value in Python, like we can do it in Matlab. Of course, it’s usually quicker just to read the article, but you’re welcome to head on over to YouTube and give it a like. Selecting ALL records when condition is met for ALL records only. Initialize the value of the product to 1 (not 0 as 0 multiplied with anything returns zero). Learn how to sum pairs of elements in Python with The Renegade Coder.
🌐
Reddit
reddit.com › r/learnpython › how do i sum product between a list and linear coefficient
r/learnpython on Reddit: How do I sum product between a list and linear coefficient
March 18, 2022 -
coefficient = [ 0.00000000e+00  0.00000000e+00  0.00000000e+00 -3.20387018e-06]

How do I multiple each coefficient to the corresponding list of values [4, 3.2, 95, 3000], such that the answer is -0.009611610540000001

[4, 3.2, 95, 3000]*coeffient_a

I did just this but it is completely wrong.

was thinking of separating them by using split but because I'm importing linear regression from sklearn, .split is not possible

🌐
Trymito
trymito.io › excel-to-python › functions › math › SUMPRODUCT
Excel to Python: SUMPRODUCT Function - A Complete Guide | Mito
To replicate the SUMPRODUCT function ... To calculate the sumproduct of two lists in Python, simply multiply the two lists and then use the `sum()` method....
Find elsewhere
🌐
Spicewithnice
spicewithnice.com › nezih-hasanoglu-fxr › python-sum-product-of-two-lists-0688d4
python sum product of two lists
* b = [2, 6, 12, 20] A list comprehension would give 16 list entries, for every combination x * y … How can I sum the product of two list items using for loop in python , Just zip the lists to generate pairs, multiply them and feed to sum : >>> a = [1,2,3] >>> b = [4,5,6] What about good ...
🌐
Python
mail.python.org › pipermail › tutor › 2010-January › 074048.html
[Tutor] multiply and sum two lists with list comprehension?
January 28, 2010 - >>> A=[1,2,3] >>> B=[2,2,2] >>> [i*j for i,j in zip(A,B)] [2, 4, 6] >>> sum([i*j for i,j in zip(A,B)]) 12 > Thanks, > Ali > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/tutor/attachments/20100128/6b0f7c56/attachment.htm> Previous message: [Tutor] multiply and sum two lists with list comprehension?
🌐
Invent with Python
inventwithpython.com › pythongently › exercise13
Exercise 13 - Sum & Product
Run it from the same folder as your sumproduct.py file so that it can import it as a module: ... When run, this program displays the million numbers between 1 and 1,000,000,000 it generated, along with the smallest number in that list. Prev - #12 Smallest & Biggest | Table of Contents | Next - #14 Average
🌐
Reddit
reddit.com › r › learnpython › comments › 3s9pa9 › sumproduct_iteratively
r/learnpython - Sumproduct iteratively
November 10, 2015 -

Hello!

I have two lists of numbers in "blocks" that I'd want to sumproduct.

list1 = ['10', '9', '', '20', '30', '1'] 
list2 = ['15', '2', '', '58', '0', '2']

By blocks I mean block 1 is the first 2 entries in the list and block 2 is the last 4 entries in the list. So the expected result is

#block1sumproduct = (10 * 15) + (9 * 2)

Block2 contains an empty value in index 2 so I'd have to skip that product and sum the rest:

Expected result:

#block2sumproduct = (20 * 58) + (30 * 0) + (1 * 2)

How can I do this iteratively like for i in range(len(list1[i]))?

What I've tried:

productlist = []
for i in range(len(list1)):
if list1[i] in ("", "N/A"):
productlist.append("")
pass
else:
productlist.append(int(list1[i]) * int(list2[i]))

However, the list doesnt know about the blocks and I don't know how to intuitively add it to the process. So when I go to sum the items in productlist I can do:

sumproductlist = {} #dictionary where the keys will be the blocks
sumproductlist[i] = productlist[i] + productlist[i+1] #where i is the number of blocks

But you see that I had to manually create the operation productlist[i] + productlist[i+1] so for the next block I'd need a new line to do productlist[i] + productlist[i+1] + productlist[i+2]which seems very unpythonic.

Top answer
1 of 4
3

Oh, so many problems in one post ;)

At first you should check if you can convert the list entries into integers. The best use case is to ask for forgivness and use try-except. That means if int(something) raises an Error, catch that specific error and handle it:

>>> def check_for_ints(entry):        try:	        return int(entry)        except ValueError:	        return None>>> check_for_ints("2")2>>> check_for_ints("")>>> check_for_ints("jhkajshkljh")

See, this will only return something that can converted to an integer.

Noe, we're taking your input lists and we're creating two new lists, with proper integers:

>>> list1 = ['10', '9', '', '20', '30', '1']>>> list2 = ['15', '2', '', '58', '0', '2']>>> inter1 = [check_for_ints(i) for i in list1 if not  check_for_ints(i) is None]>>> inter2 = [check_for_ints(i) for i in list2 if not check_for_ints(i) is None]>>> inter1[10, 9, 20, 30, 1]>>> inter2[15, 2, 58, 0, 2]

Now, we have interger lists, let us build a list of products:

>>> product = [i*j for i, j in zip(inter1, inter2)]>>> product[150, 18, 1160, 0, 2]

Finally we only have to sum it up:

>>> sum(product)1330

Or without the intermediate steps:

>>> sum(i*j for i, j in zip(        (check_for_ints(i) for i in list1 if not check_for_ints(i) is None),        (check_for_ints(i) for i in list2 if not check_for_ints(i) is None))        )1330

I used list comprehensions here, a powerful tool and shortcut, if you have problems understanding them, read this very nice piece of documentation. Good luck!

2 of 4
2

Hi! I'm working on a bot to reply with suggestions for common python problems. This might not be very helpful to fix your underlying issue, but here's what I noticed about your submission:

You are looping over an object using something like

for x in range(len(items)):    foo(item[x])

This is simpler and less error prone written as

for item in items:    foo(item)

If you DO need the indexes of the items, use the enumerate function like

for idx, item in enumerate(items):    foo(idx, item)
🌐
Real Python
realpython.com › python-sum-function
Python's sum(): The Pythonic Way to Sum Values – Real Python
July 21, 2023 - Here, dot_product() takes two sequences as arguments and returns their corresponding dot product. If the input sequences have different lengths, then the function raises a ValueError. Embedding the functionality in a custom function allows you to reuse the code. It also gives you the opportunity to name the function descriptively so that the user knows what the function does just by reading its name. ... Flattening a list of lists is a common task in Python...
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-k-summation-from-two-lists
Python - K Summation from Two lists - GeeksforGeeks
May 3, 2023 - The product() function from the itertools module is used to find the Cartesian product of test_list1 and test_list2, which will generate all possible combinations of pairs of elements from the two lists.
🌐
Stellar Grove
stellargrove.com › how-to-blog › how-to-perform-sum-product-function-in-python
How to Perform Sum Product Function in Python — Stellar Grove
May 19, 2023 - Once you have installed the NumPy library, you can import it into your Python code using the following command: ... Next, you can use the np.sum() function to calculate the sum product.
Address   Annapolis, MD USA
🌐
Delft Stack
delftstack.com › home › howto › python › calculate the dot product of two lists in python
How to Calculate the Dot Product of Two Lists in Python | Delft Stack
February 2, 2024 - Finally, we would also use the sum() function to calculate the sum of the products from the two lists of numerical values, as shown in the code below. from operator import mul num1 = [2, 4, 6, 8, 10] num2 = [10, 20, 30, 40, 50] print(sum(map(mul, ...
🌐
GeeksforGeeks
geeksforgeeks.org › python-multiply-two-list
Python - Multiply Two Lists - GeeksforGeeks
January 31, 2025 - Loop iterates over the indices of both lists a and b multiplying the corresponding elements from each list. Products are appended to the list res resulting in [4, 10, 18]. List comprehension allows multiplying two lists element-wise by iterating over their indices and applying the multiplication directly.
🌐
Quora
quora.com › How-do-I-multiply-two-lists-in-Python
How to multiply two lists in Python - Quora
Answer: list1 and list2 are the two veriable decleration list1 = [1, 2, 3] list2 = [4, 5, 6] products = [] initialize result list. #declear array products for multiplication for num1, num2 in zip(list1, list2): //looping through the array of list1 and list2 products. append(num1 * num2) //ap...