# Splitting a list of lists (part2)

This is a follow up from Splitting a list of lists .

What would be a nice way to split the list

l1 = {1,2,{a,b,c},3,{d,e}}


into

{{1,2,a,3,d},{1,2,a,3,e},{1,2,b,3,d},{1,2,b,3,e},{1,2,c,3,d},{1,2,c,3,e}}


?

You can use:

Distribute[l1, List]

• ...thank you for introducing me to Distribute! :) Nov 21, 2014 at 11:55

Here is an approach:

Tuples[Replace[l1, x_?AtomQ :> {x}, {1}]]


yields:

(*{{1, 2, a, 3, d}, {1, 2, a, 3, e}, {1, 2, b, 3, d}, {1, 2, b, 3,
e}, {1, 2, c, 3, d}, {1, 2, c, 3, e}}*)


Just an other one which is not as "simple" as the other answers:

Evaluate@With[{pos = Flatten@Position[l1, _List]},
ReplacePart[l1, Rule @@@ Thread[{pos, Slot /@ Range@Length@pos}]]] & @@@
Tuples[Variables /@ l1 /. {} :> Sequence[]]

{{1, 2, a, 3, d}, {1, 2, a, 3, e}, {1, 2, b, 3, d},
{1, 2, b, 3, e}, {1, 2, c, 3, d}, {1, 2, c, 3, e}}


Which is basically distributing

Tuples[Variables /@ l1 /. {} :> Sequence[]]

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


over

Evaluate@With[{pos = Flatten@Position[l1, _List]},
ReplacePart[l1, Rule @@@ Thread[{pos, Slot /@ Range@Length@pos}]]] &

{1, 2, #1, 3, #2}