CAB
CAB

Reputation: 1148

How to create the cartesian product of a list of lists of tuples

I'm trying to accomplish a cartesian product of a list of lists. The base elements are tuples. Something about the tuples seems to really throw product off. The more products I attempt the more it adds a rat's nesting of tuples.

Here's my code

from itertools import product

listOfListsOfTuples = [ [(1,2),], [(3,4),(5,6)] ]
got = list(product(*listOfListsOfTuples))
print('got   :',got)

wanted = [ [(1,2),(3,4)], [(1,2),(5,6)] ]
print('wanted:',wanted)

and my output

got   : [((1, 2), (3, 4)), ((1, 2), (5, 6))]
wanted: [[(1, 2), (3, 4)], [(1, 2), (5, 6)]]

Maybe I need to fall back to for loops and do it myself?

EDIT: was made aware I need a * on the call to product, so added that. That changed my output, so I changed that to my new output above. Note that got != wanted

Upvotes: 0

Views: 49

Answers (1)

Marat
Marat

Reputation: 15738

product takes iterables as a separate arguments, not as a single iterable of iterables. So, just missing a star to expand listOfListsOfTuples:

product(*listOfListsOfTuples)

Straight from the docs

itertools.product(*iterables, repeat=1)

Cartesian product of input iterables.

UPD: product will always yield tuples. To get lists, you'll need to explicitly convert:

got = [list(tuples) for tuples in product(*listOfListsOfTuples))]

Upvotes: 4

Related Questions