List manipulation: all possible sublists

Say I have the following list

{a,{b,c},{d,f,g},e}

what is the fastest way to get the result lists

resultList={{a,b,d,e},{a,c,d,e},{a,b,f,e},{a,c,f,e},{a,b,g,e},{a,c,g,e}}

That is all flattened lists with all possible combinations of the elements of the inner lists ?

I do not care about the order they're obtained in, but I do not want lists like :

{a,a,a,a} or {a,b,b,e}

Note in the inner lists {b,c} and {d,f,g}, the elements (b,c,d,f,g) are actually also lists, it is not the case for the outer elements a and d. Thank you.

• Tuples[{{a}, {b, c}, {d, f, g}, {e}}]? Jun 13, 2021 at 16:12
• Hi, yes this almost works, I'll have to tweak it a bit, a real list example is {-3, -3, -3, -3, {{-3, 3}, {-2, 2}, {-1, 1}, {0, 0}, {1, -1}, {2, -2}, {3, -3}}, {{-1, 3}, {0, 2}, {1, 1}, {2, 0}, {3, -1}}, {{3, 3}}, {{-3, -3}}, -3, -3, -3, -3} , so the first elements are not lists, while the inner elements are lists, if all elements were lists, then it would work @MichaelE2 Jun 13, 2021 at 16:19
• In addition, Level[Transpose[{lst}],{-2}]//Tuples Jun 17, 2021 at 18:36

If you cannot generate the list in a "uniform" way such that all elements are lists of integers (see this comment), then this will work on lists of the form in the comment:

Tuples@Replace[{a, {b, c}, {d, f, g}, e}, x : Except[_List] :> {x}, 1]

For the list in the comment, one could also use

Tuples@Replace[list, x_Integer :> {x}, 1]
• Excellent ! Thanks Jun 13, 2021 at 16:33
• (+1). I didn't know you could link to a comment: mathematica.stackexchange.com/q/249589/106#comment625318_249589, for example. Very cool! Jun 13, 2021 at 17:21
• @user1066 Thanks. There's link to a comment on the time stamp (which maybe you found, though you used a shorter form). Jun 13, 2021 at 17:37

Distribute with List as the second argument gives the desired result without additional processing of the input list:

Distribute[{a, {b, c}, {d, f, g}, e}, List]
{{a, b, d, e}, {a, b, f, e}, {a, b, g, e}, {a, c, d, e},
{a, c, f, e}, {a, c, g, e}}