-1

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.

vaultah
  • 44,105
  • 12
  • 114
  • 143
mlkaggle
  • 11
  • 1

1 Answers1

2
>>> 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)]
>>>
Kevin
  • 74,910
  • 12
  • 133
  • 166