-1

If I have a list data_x = [1,2,3,4], how do I multiply each element of data_x with each element of another list data_y = [2,3,4,5] and sum the values?

The answer should be 1*2 +2*3 +3*4+ 4*5 = 40. I am looking for some kind of for loop.

pushkin
  • 9,575
  • 15
  • 51
  • 95
  • 1
    https://stackoverflow.com/questions/11344827/summing-elements-in-a-list – Aran-Fey Apr 22 '18 at 12:24
  • Your example contradicts your question... (you say you want to multiply each element of `data_x` with each element of `data_y`, yet you only multiply pairs of elements with the same indices) – Adi219 Apr 22 '18 at 12:31
  • if you want to go fully functional then you could zip them and map with * (multiplication). – Oleg Apr 22 '18 at 14:53

4 Answers4

1

Use zip to perform index wise operations between two lists:

sum([x * y for x, y in zip(data_x, data_y)])

Or a numpy solution using numpy.multiply and numpy.sum:

np.multiply(data_x, data_y).sum()
Austin
  • 25,759
  • 4
  • 25
  • 48
0

Try this (using a for loop, as requested by the OP):

answer = 0
for i in range(len(data_x)):
    answer += (data_x[i] * data_y[i])

Another (quicker) way (using list comprehensions):

answer = sum([x*y for x in zip(data_x, data_y)])
## Use zip to perform index-wise operations between two lists
## zip returns a list of tuples, with each tuple at index i containing the elements of data_x[i] and data_y[i]

You could also try this (if you have numpy installed):

np.multiply(data_x, data_y).sum()
Adi219
  • 4,712
  • 2
  • 20
  • 43
0

You can use zip to do this.

data_x  = [1, 2, 3, 4]
data_y = [2, 3, 4, 5]

res = sum([a * b for a, b in zip(data_x, data_y )])
print(res)
pushkin
  • 9,575
  • 15
  • 51
  • 95
minji
  • 512
  • 4
  • 16
  • 1
    While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – Derek Brown Apr 22 '18 at 13:45
0

Use this

result = sum([x * y for x, y in zip(data_x, data_y)])

result = zip(data_x, data_y) creates a zip object of tuples where each tuple result[i] corresponds to the values data_x[i] and data_y[i]

That is if

data_x = [1, 2, 3, 4]
data_y = [2, 3, 4, 5]

Then,

result = [(1, 2), (2, 3), (3, 4), (4, 5)]
Parth Sharma
  • 95
  • 2
  • 6