I have two lists:
A = [1,2,3]
B = [4,5,6]
How do I get a new list C which should have the product of each values in the two list.
My final output should be
C = [4,5,6,8,10,12,12,15,18]
I have two lists:
A = [1,2,3]
B = [4,5,6]
How do I get a new list C which should have the product of each values in the two list.
My final output should be
C = [4,5,6,8,10,12,12,15,18]
@CDJBs answer is correct it can also be done without itertools.
[i*j for j in A for i in B]
This also works, but i think itertools is faster
While you can use itertools.product and work with lists as other answers suggest, I would recommend going with NumPy here. You can use np.multiply.outer and flatten the result with ravel:
A = np.array([1,2,3])
B = np.array([4,5,6])
np.multiply.outer(A,B).ravel()
# array([ 4, 5, 6, 8, 10, 12, 12, 15, 18])
You can use itertools.product for this, to iterate over all pairwise combinations of A and B.
>>> import itertools
>>> C = [a*b for a,b in itertools.product(A,B)]
>>> C
[4, 5, 6, 8, 10, 12, 12, 15, 18]
A = [1,2,3]
B = [4,5,6]
C= []
for i in A:
for j in B:
C.append(int(i)*int(j))
I timeited @yatu's, @cdjb's and @shadesfear's solutions just out of curiosity. Numpy is the fastest, Itertools is the slowest. The difference is so huge, it makes me doubt my understanding of how Numpy works here:
>>> import timeit
>>>
>>> setup_nested_for = 'A = [i for i in range(256)]; B = [i for i in range(256)]'
>>> setup_itertools = 'import itertools; ' + setup_nested_for
>>> setup_numpy = 'import numpy; A = numpy.array([i for i in range(256)]); B = numpy.array([i for i in range(256)])'
>>>
>>> timeit.timeit(stmt='[a * b for a in A for b in B]', setup=setup_nested_for, number=10000)
37.95282502599912
>>> timeit.timeit(stmt='[a * b for a, b in itertools.product(A, B)]', setup=setup_itertools, number=10000)
47.30394076399898
>>> timeit.timeit(stmt='numpy.multiply.outer(A, B).ravel()', setup=setup_numpy, number=10000)
1.2109698210006172