Search code examples
python-3.xpython-itertools

How to past a list of lists to a function expecting *iterables


I want the cartesian product of a bunch of lists.

from itertools import product

v1=['a','b','c']
v2=['1','2']
v3=['x','y','z']
list(product(v1,v2,v3))

This returns the desired result:

[('a', '1', 'x'),
 ('a', '1', 'y'),
 ('a', '1', 'z'),
 ('a', '2', 'x'),
 ('a', '2', 'y'),
 ('a', '2', 'z'),
 ('b', '1', 'x'),
 ('b', '1', 'y'),
 ('b', '1', 'z'),
 ('b', '2', 'x'),
 ('b', '2', 'y'),
 ('b', '2', 'z'),
 ('c', '1', 'x'),
 ('c', '1', 'y'),
 ('c', '1', 'z'),
 ('c', '2', 'x'),
 ('c', '2', 'y'),
 ('c', '2', 'z')]

However, I don't know the number of lists in advance. Suppose I have them stored as a list of lists vs, and I try to do this:

vs=[v1,v2,v3]
list(product(vs))

Of course, that doesn't give me what I want, because it treats vs as a single argument instead of multiple arguments.

[(['a', 'b', 'c'],), (['1', '2'],), (['x', 'y', 'z'],)]

Is there a way that I can pass a list of lists into product and have it operate on the sublists?


Solution

  • Try using a starred expression list(product(*vs))