0

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)]?

Kurt Peek
  • 52,165
  • 91
  • 301
  • 526

3 Answers3

2

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)]
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
2

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)]
Silas Parker
  • 8,017
  • 1
  • 28
  • 43
2

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)]
Tonechas
  • 13,398
  • 16
  • 46
  • 80