7

I have input like:

x = [[1,2,3],[1,2,3,4],[1,2,3,4,5]]

I want to choose one item from each sublist of a list, and - maintaining order - make every possible combination with them, like:

[[1,1,1],[1,1,2],[1,1,3],[1,1,4],[1,1,5],[1,2,1]...]

Each sub-list in the output should include one item from each input sub-list - i.e.: it does not include [5,5,5] or [4,4,5], because the first input sub-list does not include 4, and only the last includes 5. Order matters: the output should include [3,4,5], but not [5,4,3].

How can I get an exhaustive list of results meeting these criteria? I was hoping there would be an itertools function for this, but I have not been able to find one.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
5813
  • 1,073
  • 3
  • 14
  • 28

1 Answers1

12

I think you want itertools.product

[p for p in itertools.product(*x)]
tacaswell
  • 84,579
  • 22
  • 210
  • 199