1

What is a Pythonic way to make combined tuple from a list?

e.g. From:

a = [['A','B','C'], ['D', 'E', 'F']]

To:

[('A','D'), ('A', 'E'), ..., ('C', 'E'), ('C','F')]
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
alnet
  • 1,093
  • 1
  • 12
  • 24

2 Answers2

3

Use itertools.product. If you have a list of lists, use the "splat" operator, *, to unpack them. product takes an arbitrary number of iterables:

>>> a = [['A', 'B'], ['C', 'D'], ['E', 'F']]
>>> list(itertools.product(*a))

[('A', 'C', 'E'),
 ('A', 'C', 'F'),
 ('A', 'D', 'E'),
 ('A', 'D', 'F'),
 ('B', 'C', 'E'),
 ('B', 'C', 'F'),
 ('B', 'D', 'E'),
 ('B', 'D', 'F')]
jme
  • 19,895
  • 6
  • 41
  • 39
  • You can unpack the list with `list(product(*a))` – Akavall Oct 29 '15 at 15:08
  • Is there a generic way if I don't know the length of the list? e.g. a= [['A', 'B'], ['C', 'D'], ['E', 'F']]? – alnet Oct 29 '15 at 15:09
  • @alnet Yep, just use Akavall's hint. I'll add it to the answer. – jme Oct 29 '15 at 15:09
  • 1
    Yes this is the right answer. But it has been asked and answered before, can you guys help close this question as dupe please? – Tim Oct 29 '15 at 15:13
0

Using a list comprehension:

[(x,y) for x in a[0] for y in a[1]]
Stephan W.
  • 188
  • 13