0

I have m-length list of tuples.
For example:

m = 2
mylist = [(1, 2), (3, 4)]

I need to get all combinations of these tuples, using only one element from one tuple:

[1, 3]
[1, 4]
[2, 3]
[2, 4]

For m=3:

mylist = [(1, 2), (3, 4), (5, 6)]

[1, 3, 5]
[1, 3, 6]
[1, 4, 5]
[1, 4, 6]
[2, 3, 5]
[2, 3, 6]
[2, 4, 5]
[2, 4, 6]

Is there any good way to do it for any m?

Angelika
  • 200
  • 3
  • 16
  • You can probably use some combination of [`zip`](https://docs.python.org/3.8/library/functions.html#zip) and [`itertools.combinations`](https://docs.python.org/3/library/itertools.html) or the like. But I'm not sure I 100% understand your requirements. You said "one element from one tuple", but you used two elements from one tuple. – kojiro Oct 25 '20 at 16:19
  • @kojiro, I mean in each combination I can use only one element from each tuple, for example I can't do `[1, 2, 3]` or `[1, 2, 3, 4]` – Angelika Oct 25 '20 at 16:20
  • Can you add an example where the first element of the resulting pairs comes from a tuple that is not the _first_ tuple in `my_list`? – kojiro Oct 25 '20 at 16:21
  • Does this answer your question? [All combinations of a list of lists](https://stackoverflow.com/questions/798854/all-combinations-of-a-list-of-lists) - `list(itertools.product(*my_list))` – Tomerikoo Oct 25 '20 at 16:22
  • `itertools.product` is probably what you're looking for – MarcMush Oct 25 '20 at 16:23
  • @Tomerikoo, It does, thank you a lot! – Angelika Oct 25 '20 at 16:26
  • Great, so mark it as a duplicate or delete the question. And try to do some research before asking. I'm only saying that for your own benefit. I can only imagine the time and effort it took you to write this question. This could all be saved by simply Googling `python all combinations of a list of tuples` – Tomerikoo Oct 25 '20 at 16:26

1 Answers1

1

You can use itertools.product:

import itertools

for el in itertools.product(*mylist):
    print(el)

Outputs:

(1, 3)
(1, 4)
(2, 3)
(2, 4)

Ref. https://docs.python.org/3/library/itertools.html#itertools.product

Grzegorz Skibinski
  • 12,624
  • 2
  • 11
  • 34