How to Pythonically generate lists of variable length containing exhuastive combinations of specified values?

Question:

I’m hoping that there’s a ‘Pythonic’ way to do this. Let’s say that I have a list and an integer.

foo = [1, 2]
bar = 2

I want to return a series of lists where each list is the length specified by the integer (or length -1), where the lists represent an expression of each possible combination of values in the list. So for instance, the output I’m looking for would be something like this:

>> [[1, 1], [1, 2], [2, 1], [2, 2]]

if bar was equal to three, then:

>> [[1, 1, 1], [1, 1, 2], [1, 2, 2], [2, 1, 2], [2, 2, 1], [1, 2, 1], [2, 1, 1], [2, 2, 2]]

… and so on.

Asked By: mlkaggle

||

Answers:

>>> import itertools
>>> foo = [1,2]
>>> list(itertools.product(foo, repeat=2))
[(1, 1), (1, 2), (2, 1), (2, 2)]
>>> list(itertools.product(foo, repeat=3))
[(1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 2, 2), (2, 1, 1), (2, 1, 2), (2, 2, 1), (2, 2, 2)]
>>>
Answered By: Kevin
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.