Search code examples
pythonlistpython-itertoolssublist

How can I choose one item from every list, making every possible combination?


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.


Solution

  • I think you want itertools.product

    [p for p in itertools.product(*x)]