# How to Flatten {1, {2, {3, 4}, 5}, 6} into {1, {2, 3, 4, 5}, 6}

I've tried 3 methods but all failed to do that.

1st Method

Apply[Flatten, {1, {2, {3, 4}, 5}, 6}, {2}]


2nd Method

Map[Flatten, {1, {2, {3, 4}, 5}, 6}, {2}]


3rd Method

Flatten[{1, {2, {3, 4}, 5}, 6}, {2}]


I wanna get {1, {2, 3, 4, 5}, 6}

• This problem is very underspecified. You might be asking "flatten the deepest level across everything" like {a, {b, c}, {d e}, f} -> {a,b,c,d,e,f}. You might be asking "assuming things are nested x -> (A x B), flatten the deepest" (not the case since presumably you want this to also work on {1,{2,3,4,5},6}). You might be asking "flatten the second element". You might be asking "flatten the second element by one level". You need to either specify the problem unambiguously, and/or provide like 10 all-encompassing edge-case examples (e.g. the empty list, etc.). – ninjagecko Jan 29 '20 at 7:05

lst = {1, {2, {3, 4}, 5}, 6};
FlattenAt[lst, {2, 2}]


{1, {2, 3, 4, 5}, 6}

Also

Map[## & @@ # &, lst, {2}]


{1, {2, 3, 4, 5}, 6}

Replace[lst, List -> Sequence, {3}, Heads -> True]


{1, {2, 3, 4, 5}, 6}

And

☺ = ## & @@@ # & /@ # &;
☺ @ lst


{1, {2, 3, 4, 5}, 6}

• Because this is an accepted answer, I suppose it is important to note a principal difference between FlattenAt[lst, {2, 2}] and the rest of the examples: FlattenAt flattens position, while, for example, Replace[lst, List -> Sequence, {3}, Heads -> True] flattens level. – Anton.Sakovich Jan 29 '20 at 13:16

Replace[l_List :> Flatten[l]] /@ {1, {2, {3, 4}, 5}, 6}


{1, {2, 3, 4, 5}, 6}

• Is it possible to do this with Apply? – kile Jan 28 '20 at 12:47
• Using Apply doesn't make much sense with Flatten, since Flatten is a single-argument function (It does have an infrequently-used but useful second argument, but still). Apply is more useful for multi-argument functions like Join, List, and Plus. Technically, Flatten[{##}] & @@@ {1, {2, {3, 4}, 5}, 6} works, but only because 1 and 6 are atomic. It wouldn't work with, e.g., {Sin, {2, {3, 4}, 5}, Sin}, so it's not a very good way to do what you want. – Sjoerd Smit Jan 28 '20 at 13:01

This will work:

l = {1, {2, {3, 4}, 5}, 6}
MapAt[Flatten, l, 2]


{1, {2, 3, 4, 5}, 6}

also:

# /. x_ /; Length[x] > 1 :> Flatten@x & /@ l


{1, {2, 3, 4, 5}, 6}

A couple more:

list = {1, {2, {3, 4}, 5}, 6};

Apply[## &, list, {2}]

Flatten[{##}] & @@@ list


Also if you are looking for specific level control consider levelspec in Replace. For example with:

rl = {a_, x__, z_} :> {a, {x} /. rl, z};
deep = Range /. rl

{1, {2, {3, {4, {5, {6, {7, 8}, 9}, 10}, 11}, 12}, 13}, 14}


Then:

Replace[deep, {x__} :> x, {3, 5}]

{1, {2, {3, 4, 5, 6, {7, 8}, 9, 10, 11, 12}, 13}, 14}


Related:

lst[]=Flatten@lst[];lst


{1, {2, 3, 4, 5}, 6}