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]
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]
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]
Try inbuilt function zip
and list comprehension :
z = [i*j for i,j in zip(x,y)]
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)
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]
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]