-3

Given a list as follows:

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

I know it's very easy to combine the list of tuples by using itertools.

(1, 3, 6), (1, 4, 6), (1, 5, 6), (2, 3, 6), (2, 4, 6), (2, 5, 6)

But how can I solve it without using itertools?

marshallslee
  • 645
  • 1
  • 8
  • 22
  • Despite the nice answers below, you should have a look at [this SE answer](https://stackoverflow.com/a/35608701/803359) – mikuszefski Jun 02 '20 at 06:33

3 Answers3

1
 [(x, y, 6) for x in (1, 2) for y in (3, 4, 5)]

Also see Get the cartesian product of a series of lists? for more general solutions

Serge
  • 3,387
  • 3
  • 16
  • 34
1

Here's a fairly generic approach with a series of loops over the input:

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

result = [tuple([l]) for l in lst[0]]
for l in lst[1:]:
    out = []
    for r in result:
        for i in range(len(l)):
            out.append((*r, l[i]))
    result = out

print(result)

Output:

[(1, 3, 6), (1, 4, 6), (1, 5, 6), (2, 3, 6), (2, 4, 6), (2, 5, 6)]
Nick
  • 138,499
  • 22
  • 57
  • 95
0
def product(pools):
    result = [[]]
    for pool in pools:
        result = [x+[y] for x in result for y in pool]
    return result

product([(1,2,3),(4,5),(6,)])
[[1, 4, 6], [1, 5, 6], [2, 4, 6], [2, 5, 6], [3, 4, 6], [3, 5, 6]]
Onyambu
  • 67,392
  • 3
  • 24
  • 53
  • 3
    While the code seems obvious for many, please add some explanation to your only code answer. Also note that you are not returning tuples. – mikuszefski Jun 02 '20 at 06:24
  • 1
    While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. [From Review](/review/low-quality-posts/26294560) – double-beep Jun 02 '20 at 16:21