Search code examples
pythonpython-2.7productpython-itertools

Cartesian product of n copies of an iterator with n variable


I would like to use itertools.product or a similar command in order to obtain the cartesian product of n copies of an iterator iter with itself, where n is a variable. I tried constructing it recursively by

import itertools

prod_iter = iter
for i in xrange(n-1):
    prod_iter = itertools.product(prod_iter,iter)

But starting with, say, iter=xrange(2), n=3 and running

for i in prod_iter:
    print i

I get as an output

((0,0),0)
((0,0),1)
((0,1),0)
...

and not

(0,0,0)
(0,0,1)
(0,1,0)
...

as I would like. Is there a way to do this?


Solution

  • itertools.product has such parameter: repeat.

    So no need to invent it yourself, you can simply write:

    from itertools import product
    
    for i in product(iter, repeat=3):
        print i

    For example:

    >>> from itertools import product
    >>> 
    >>> iter = "qux"
    >>> 
    >>> for i in product(iter, repeat=3):
    ...     print i
    ... 
    ('q', 'q', 'q')
    ('q', 'q', 'u')
    ('q', 'q', 'x')
    ('q', 'u', 'q')
    ('q', 'u', 'u')
    ('q', 'u', 'x')
    ('q', 'x', 'q')
    ('q', 'x', 'u')
    ('q', 'x', 'x')
    ('u', 'q', 'q')
    ('u', 'q', 'u')
    ('u', 'q', 'x')
    ('u', 'u', 'q')
    ('u', 'u', 'u')
    ('u', 'u', 'x')
    ('u', 'x', 'q')
    ('u', 'x', 'u')
    ('u', 'x', 'x')
    ('x', 'q', 'q')
    ('x', 'q', 'u')
    ('x', 'q', 'x')
    ('x', 'u', 'q')
    ('x', 'u', 'u')
    ('x', 'u', 'x')
    ('x', 'x', 'q')
    ('x', 'x', 'u')
    ('x', 'x', 'x')