0

How can I multiply every element of two linear arrays with each other, i.e. if I got these two arrays:

x=[1, 4, 0 ,3]
y=[2, 1, 9 ,4]

I would like to get the following one as the output :

z=[2, 4, 0, 12]
Arkistarvh Kltzuonstev
  • 6,824
  • 7
  • 26
  • 56
Lpng
  • 109
  • 1
  • 8
  • If you want to work with numpy as it seems, you need to define them as numpy arrays, so: `np.array([1, 4, 0 ,3])`. Then you just need to multiply them ( `*`) – yatu Mar 11 '19 at 09:24

5 Answers5

2

using a list comprehension is one way; using zip to iterate over both lists simultaneously:

z = [a * b for a, b in zip(x, y)]

a different way is to use numpy:

import numpy as np

x = np.array([1, 4, 0 ,3])
y = np.array([2, 1, 9 ,4])

z = x * y
print(z)  # [ 2  4  0 12]
hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
1

Try inbuilt function zip and list comprehension :

z = [i*j for i,j in zip(x,y)]
Arkistarvh Kltzuonstev
  • 6,824
  • 7
  • 26
  • 56
0

You can use .zip() to accomplish just that

Using list comprehension:

[x*y for x,y in zip(list_x,list_y)]

Without list comprehension:

for x,y in zip(list_x,list_y):
    print(x*y)
Fester
  • 49
  • 3
  • 13
0

Here you have a different option:

>>> x=[1, 4, 0 ,3]
>>> y=[2, 1, 9 ,4]
>>> import operator
>>> list(map(operator.mul, x, y))
[2, 4, 0, 12]
Netwave
  • 40,134
  • 6
  • 50
  • 93
0

The multiplication of two array is only possible when size of both arrays are equal in length.

Try this code !

Code :

x=[1, 4, 0 ,3]
y=[2, 1, 9 ,4]
z= []
if (len(x)==len(y)):
    for i in range(0,len(x)):
        z.append(x[i]*y[i])
    print(z)
else:
    print("Array are not equal in size.... Multiplication is not possible")

Output :

[2, 4, 0, 12]
Usman
  • 1,983
  • 15
  • 28