0

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]
CDJB
  • 13,204
  • 5
  • 27
  • 47
Digvijay
  • 25
  • 1
  • Also: [Multiply all combinations of two lists](https://stackoverflow.com/q/48143308/7851470) – Georgy Feb 18 '20 at 09:27
  • Duplicate for NumPy: [Multiplying every element of one array by every element of another array](https://stackoverflow.com/q/30587076/7851470) – Georgy Feb 18 '20 at 09:29

5 Answers5

6

@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

Shadesfear
  • 697
  • 3
  • 14
6

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])
yatu
  • 80,714
  • 11
  • 64
  • 111
5

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]
CDJB
  • 13,204
  • 5
  • 27
  • 47
2
A = [1,2,3]
B = [4,5,6] 
C= []
for i in A:
  for j in B:
    C.append(int(i)*int(j))
David Buck
  • 3,594
  • 33
  • 29
  • 34
ritvika
  • 21
  • 3
2

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