For example, if I want values in list a to multiply with values of the same position in list B :
A = [1,2,3] B = [4,5,6] Then the desired calculations are: 1 multiplied by 4, 2 multiplied by 5 and 3 multiplied by6
For example, if I want values in list a to multiply with values of the same position in list B :
A = [1,2,3] B = [4,5,6] Then the desired calculations are: 1 multiplied by 4, 2 multiplied by 5 and 3 multiplied by6
Iterate through two lists at a time using the zip
function.
A = [1, 2, 3]
B = [4, 5, 6]
C = []
for a, b in zip(A, B):
C.append(a*b)
print(C)
# Prints [4, 10, 18]
Using list comprehension (faster than for loop):
>>> res_list = [ls1[i] * ls2[i] for i in range(len(ls1))]
OR
Numpy (fastest method) :
>>> import numpy as np
>>> ls1 = np.array([1,2,3,4])
>>> ls2 = np.array([2,1,6,5])
>>> res = ls1 * ls2
>>> print(res)
array([2,3,18,20])
OR
for loop (slowest but easily readable) :
res= []
for i in range(len(a)):
res.append(ls1[i]*ls2[i])
print(res)
Edit: Kindly check this speed performance graph from freeCodeCamp
If you're looking for a one-liner, you can use list comprehension for this:
C = [x*y for x, y in zip(A, B)]
References:
Here are two ways to do it:
The more "Pythonic" way to do it is list comprehension:
A = [1, 2, 3]
B = [4, 5, 6]
C = [a * b for a, b in zip(A, B)] # [4, 10, 18]
Another way is to iterate on both of the lists with the function zip()
:
A = [1, 2, 3]
B = [4, 5, 6]
C = []
for a,b in zip(A, B):
result = a * b
C.append(result)
# C = [4, 10, 18]
Good Luck!