56

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.

martineau
  • 119,623
  • 25
  • 170
  • 301
W7GVR
  • 1,990
  • 1
  • 18
  • 24
  • 1
    You already have the answers below, but this has some good use cases for the itertools product function: https://www.hackerrank.com/challenges/itertools-product – Afflatus Sep 16 '16 at 19:31

3 Answers3

74
>>> 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).

interjay
  • 107,303
  • 21
  • 270
  • 254
40
>>> 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)]
rkhayrov
  • 10,040
  • 2
  • 35
  • 40
  • 11
    does having an asterix prefix an array have special meaning in python or is this just something specific to itertools.product? – Ominus Apr 02 '14 at 20:12
  • 7
    See http://stackoverflow.com/q/5239856/395857 and [Unpacking Argument Lists](https://docs.python.org/2/tutorial/controlflow.html#unpacking-argument-lists). – Franck Dernoncourt Apr 13 '14 at 22:07
1

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

Wojciech Moszczyński
  • 2,893
  • 21
  • 27