-1

If I have the list my_list = [['a', 'b'], ['c', 'd', 'e'], how can I create a list of all possible tuples where each tuple contains a single element from each sublist? For example:

('a', 'e') is valid
('a', 'b') is invalid
('b', 'c') is valid
('c', 'd') is invalid

Importantly, my_list can contain any number of elements (sublists) and each sublist can be of any length. I tried to get a recursive generator off the ground, but it's not quite there.

I’d like to try and use recursion rather than itertools.

The logic was to iterate through 2 sublists at a time, and store those results as input to the next sublist's expansion.

def foil(lis=l):
    if len(lis) == 2:
        for x in l[0]:
            for y in l[1]:
                yield x + y
    else:
        for p in foil(l[:-1]):
            yield p


for i in foil():
    print(i)

However, this obviously only works for the len(my_list) == 2. It also needs to work with, say, my_list = [['a'], ['b'], ['c', 'd']] which would return:

('a', 'b', 'c')
('a', 'b', 'd')

Cheers!

Harry Stuart
  • 1,781
  • 2
  • 24
  • 39

1 Answers1

3

Use itertools.product:

import itertools

my_list = [['a', 'b'], ['c', 'd', 'e']]
print(list(itertools.product(*my_list)))
# [('a', 'c'), ('a', 'd'), ('a', 'e'), ('b', 'c'), ('b', 'd'), ('b', 'e')]

my_list = [['a'], ['b'], ['c', 'd']]
print(list(itertools.product(*my_list)))
#[('a', 'b', 'c'), ('a', 'b', 'd')]
Lante Dellarovere
  • 1,838
  • 2
  • 7
  • 10