Skip to content Skip to sidebar Skip to footer

Product Of Every Element Of Two Linear Arrays

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 o

Solution 1:

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]

Solution 2:

Try inbuilt function zip and list comprehension :

z = [i*j for i,j in zip(x,y)]

Solution 3:

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]

Solution 4:

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 inzip(list_x,list_y):
    print(x*y)

Solution 5:

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]

Post a Comment for "Product Of Every Element Of Two Linear Arrays"