1

I need to calculate the cartesian product of the elements of a few lists. It seems that the best way to do this is to use itertools, and in particular itertools.product. Now, the lists I want to use are themselves contained in a list, and I cannot just use the bigger list for itertools.product. I was wondering how I should extract the lists to make them usable with itertools.product.

Here is an example that shows the problem:

import itertools

elements=[[1, 2], [3, 4]]
product=itertools.product(elements)
print product

This prints [([1, 2],), ([3, 4],)]. What I wanted instead is something equivalent to the following but where I don't have to give all elements of "elements" singularly:

product=itertools.product(elements[0], elements[1])
print product

which prints [(1, 3), (1, 4), (2, 3), (2, 4)].

Thanks.

whatamess
  • 243
  • 2
  • 12

1 Answers1

4

Unpack the lists in your list with the star operator * to apply the product to your sublists.

product=list(itertools.product(*elements))
miradulo
  • 28,857
  • 6
  • 80
  • 93