How to roll-out (NOT FLATTEN) a list of lists in Python

Question:

Say I have a list of lists:

my_list = [["a"], ["b"], ["c", "d"], ["e", "f", "g"]]

I would like a function that gives each possible combination of elements:

output = [["a","b","c","e"],["a","b","d","e"],["a","b","c","f"],["a","b","d","f"],["a","b","c","g"],["a","b","d","g"]]

Note that the number of elements in the initial list is the same of the number of elements in the output sublists. The number of output sublists is the product of the lengths of the input sublists.

I don’t believe this can be done through list comprehension but I may be wrong.

Asked By: Mike J

||

Answers:

This will do the trick:

from itertools import product

list(product(*my_list))

outputs:

[('a', 'b', 'c', 'e'), ('a', 'b', 'c', 'f'), ('a', 'b', 'c', 'g'), ('a', 'b', 'd', 'e'), ('a', 'b', 'd', 'f'), ('a', 'b', 'd', 'g')]
Answered By: Christian Sloper
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.