Python itertools product of indefinite dimension

Question:

I would like to generate a Cartesian product of N variables, N being itself a variable. Let table be a list, how can I get the cartesian product of [0, table[i] - 1] for all i?
If I knew that table‘s length is always 3, I would write itertools.product(xrange(table[0]), xrange(table[1]), xrange(table[2])). But how to do that with an undefined table length?
Thanks for any help.

Asked By: Yuufo

||

Answers:

You want to use Python’s “splat” operator func(*iterable).

>>> import itertools
>>> table = [1, 5, 3]
>>> iterator = itertools.product(*map(xrange, table))
>>> list(iterator)
[(0, 0, 0), (0, 0, 1), (0, 0, 2),
(0, 1, 0), (0, 1, 1), (0, 1, 2),
(0, 2, 0), (0, 2, 1), (0, 2, 2),
(0, 3, 0), (0, 3, 1), (0, 3, 2),
(0, 4, 0), (0, 4, 1), (0, 4, 2)]
Answered By: Alyssa Haroldsen

One way would be using list comprehensions:

itertools.product(*[xrange(t) for t in table])
Answered By: KurzedMetal