+2 votes
in Programming Languages by (73.8k points)
How to find the cartesian product of two Python lists?

E.g.

a=[1,2,3]

b=[4,5]

a X b = [(1, 4), (1, 5), (2, 4), (2, 5), (3, 4), (3, 5)]

1 Answer

+1 vote
by (349k points)
selected by
 
Best answer

You can use itertools.product() for the cartesian product of lists. Check the following example:

>>> from itertools import product
>>> a=[1,2,3]
>>> b=[4,5]
>>> list(product(a,b))
[(1, 4), (1, 5), (2, 4), (2, 5), (3, 4), (3, 5)]
>>> c=[6,7]
>>> list(product(a,b,c))
[(1, 4, 6), (1, 4, 7), (1, 5, 6), (1, 5, 7), (2, 4, 6), (2, 4, 7), (2, 5, 6), (2, 5, 7), (3, 4, 6), (3, 4, 7), (3, 5, 6), (3, 5, 7)]


...