Python Forum

Full Version: Generate Cartesian Products with Itertools Incrementally
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

I know I can get Cartesian products using
itertools.product(a,b)
Assuming that
a = ['a','b']
and
b = ['1','2']
the result would be (a1,a2,b1,b2).

How can I get the result (a,b,a1,a2,b1,b2)? That is, how can I get the shortest possible products first and then increment to the longest ones?

Thanks
The first two elements of the list you want aren't products at all, unless you extend the range of possibilities like a = ['', 'a', 'b'].

If you do that, then you could generate them and sort the result. But I'm not sure I understand exactly what list you want.

>>> a = ['', 'a', 'b']
>>> b = ['', '1', '2']
>>> sorted(["".join(x) for x in product(a,b)], key=len)
['', '1', '2', 'a', 'b', 'a1', 'a2', 'b1', 'b2']
I actually figured it out.

incremental_append = []

for characterSet in (a,b):
    incremental_append.append(char)
    for result in itertools.product(*incremental_append):
        print(result)
Thank you anyways for the help.