PYTHON – Output every possible outcome from a set of multiple choices?

Question:

This is very basic but I don’t know hot to go about it.

Suppose I have a list of “choices” as an input. For example:

c = [2,3,2]

This represents 3 choices with 2 options, 3 options, then 2 options. As an output I need something like:

[1,1,1]
[1,1,2]
[1,2,1]
[1,2,2]
[1,3,1]
[1,3,2]
[2,1,1]
[2,1,2]
[2,2,1]
[2,2,2]
[2,3,1]
[2,3,2]

So each permutation of choices. I know how I’d do it if it was the same amount of choices each time (3 in the example) but I need it to work for any number of choices. I have no doubt this has been asked before but the terminology I’m searching with isn’t turning anything up.

Asked By: user2036366

||

Answers:

This can be done with itertools.product() and a list comprehension:

>>> list(itertools.product(*[range(1, j+1) for j in c]))
[(1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 2, 2), (1, 3, 1), (1, 3, 2), (2, 1, 1), (2, 1, 2), (2, 2, 1), (2, 2, 2), (2, 3, 1), (2, 3, 2)]

We loop through your list, and create a range representing the potential values for each column.

>>> [range(1, j+1) for j in c]
[range(1, 3), range(1, 4), range(1, 3)]

(I use 3.x, and range() gives a generator, in 2.x, it’ll be a list, e.g: [[1, 2], [1, 2, 3], [1, 2]], either way it works – as you consume it here anyway, it isn’t worth using xrange() in 2.x unless you particularly feel like it).

Then we unpack this into itertools.product() which gives us all the possible combinations, which is what you want.

Answered By: Gareth Latty
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.