Search code examples
pythonpython-itertools

Cartesian product of a list of sets in python


I had a list of sets. I do not know the length of the list apriori. I wanted to find the Cartesian product of the sets in the list in some code I'm writing.

For example: I have

list_of_sets=[set(['A']),set(['A','B','C']), set('D','E')];

I want to output a cartesian product of these sets, which would be,

('A', 'A', 'E')
('A', 'A', 'D')
('A', 'C', 'E')
('A', 'C', 'D')
('A', 'B', 'E')
('A', 'B', 'D')

If I knew that the list had size 3 in advance, I could use the following code to generate this cartesian product.

for i in itertools.product(list_of_sets[0],list_of_sets[1],list_of_sets[2]):
    print i

Is there an easy way to do this when I do not know the size of the list?


Solution

  • Use itertools.product(*list_of_sets).