How to apply itertools.product to elements of a list of lists?

PythonItertoolsCartesian Product

Python Problem Overview


I have a list of arrays and I would like to get the cartesian product of the elements in the arrays.

I will use an example to make this more concrete...

itertools.product seems to do the trick but I am stuck in a little detail.

arrays = [(-1,+1), (-2,+2), (-3,+3)];

If I do

cp = list(itertools.product(arrays));

I get

cp = cp0 = [((-1, 1),), ((-2, 2),), ((-3, 3),)]

But what I want to get is

cp1 = [(-1,-2,-3), (-1,-2,+3), (-1,+2,-3), (-1,+2,+3), ..., (+1,+2,-3), (+1,+2,+3)].

I have tried a few different things:

cp = list(itertools.product(itertools.islice(arrays, len(arrays))));
cp = list(itertools.product(iter(arrays, len(arrays))));

They all gave me cp0 instead of cp1.

Any ideas?

Thanks in advance.

Python Solutions


Solution 1 - Python

>>> list(itertools.product(*arrays))
[(-1, -2, -3), (-1, -2, 3), (-1, 2, -3), (-1, 2, 3), (1, -2, -3), (1, -2, 3), (1, 2, -3), (1, 2, 3)]

This will feed all the pairs as separate arguments to product, which will then give you the cartesian product of them.

The reason your version isn't working is that you are giving product only one argument. Asking for a cartesian product of one list is a trivial case, and returns a list containing only one element (the list given as argument).

Solution 2 - Python

>>> arrays = [(-1,+1), (-2,+2), (-3,+3)]
>>> list(itertools.product(*arrays))
[(-1, -2, -3), (-1, -2, 3), (-1, 2, -3), (-1, 2, 3), (1, -2, -3), (1, -2, 3), (1, 2, -3), (1, 2, 3)]

Solution 3 - Python

you can do it in three rurch using itertools.product

lst=[]
arrays = [(-1,+1), (-2,+2), (-3,+3)]  

import itertools 

for i in itertools.product(*arrays):
         lst.append(i)



print(lst)

enter image description here

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionW7GVRView Question on Stackoverflow
Solution 1 - PythoninterjayView Answer on Stackoverflow
Solution 2 - PythonrkhayrovView Answer on Stackoverflow
Solution 3 - PythonWojciech MoszczyńskiView Answer on Stackoverflow