5
$\begingroup$

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.

$\endgroup$
3
  • 3
    $\begingroup$ Tuples[{{a}, {b, c}, {d, f, g}, {e}}]? $\endgroup$
    – Michael E2
    Jun 13, 2021 at 16:12
  • $\begingroup$ 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 $\endgroup$
    – DarkBulle
    Jun 13, 2021 at 16:19
  • $\begingroup$ In addition, Level[Transpose[{lst}],{-2}]//Tuples $\endgroup$
    – user1066
    Jun 17, 2021 at 18:36

2 Answers 2

7
$\begingroup$

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]
$\endgroup$
3
  • $\begingroup$ Excellent ! Thanks $\endgroup$
    – DarkBulle
    Jun 13, 2021 at 16:33
  • $\begingroup$ (+1). I didn't know you could link to a comment: mathematica.stackexchange.com/q/249589/106#comment625318_249589, for example. Very cool! $\endgroup$
    – user1066
    Jun 13, 2021 at 17:21
  • 1
    $\begingroup$ @user1066 Thanks. There's link to a comment on the time stamp (which maybe you found, though you used a shorter form). $\endgroup$
    – Michael E2
    Jun 13, 2021 at 17:37
9
$\begingroup$

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}}
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.