Suppose we have two lists a
and b
:
a = [1, 2]
b = [3, 4]
Is there a quick operation that will return the list of tuples [(1,3), (1,4), (2,3), (2,4)]
?
A list comprehension does it:
[(i,j) for i in a for j in b]
Output:
>>> a = [1, 2]
>>> b = [3, 4]
>>> [(i,j) for i in a for j in b]
[(1, 3), (1, 4), (2, 3), (2, 4)]
You can also use itertools.product
:
list(itertools.product(a, b))
This is useful if you have several lists, or a variable number of lists.
For example:
>>> import itertools
>>> a = [1, 2]
>>> b = [3, 4]
>>> c = [5, 6]
>>> list(itertools.product(a, b, c))
[(1, 3, 5), (1, 3, 6), (1, 4, 5), (1, 4, 6), (2, 3, 5), (2, 3, 6), (2, 4, 5), (2, 4, 6)]
The function itertools.product()
will do the trick:
In [41]: a, b = [1, 2], [3, 4]
In [42]: from itertools import product
In [43]: list(product(a, b))
Out[43]: [(1, 3), (1, 4), (2, 3), (2, 4)]
It is important to point out that you need to invoke the built-in function list()
to convert the iterator returned by product
into a list.
As a side note, if your goal is that of computing the product of a list with itself, you may find it handy to use the optional repeat
keyword argument:
In [46]: list(product(a, repeat=3))
Out[46]:
[(1, 1, 1),
(1, 1, 2),
(1, 2, 1),
(1, 2, 2),
(2, 1, 1),
(2, 1, 2),
(2, 2, 1),
(2, 2, 2)]