# How to remove extra levels in list [duplicate]

My question is how to turn a 4-level matrix (notice one extra level)

A = {{{{1, 2, 3}, {4, 5, 6}}}, {{{7, 8, 9}, {10, 11, 12}}}};


into the following:

B = {{{1, 2, 3}, {4, 5, 6}}, {{7, 8, 9}, {10, 11, 12}}};


I think Flatten might do the job but I was unable to understand how it works, especially with these matrix second argument.

So a more general question: is there a way to detect extra levels and eliminate them all together?

I am using Mathematica 10.4.1

• Either B = Flatten[A, 1] or B = Join @@ A works. Commented Aug 1, 2016 at 23:06
• That doesn't work. Commented Aug 1, 2016 at 23:07
• Sorry, that was a typo. Commented Aug 1, 2016 at 23:07
• Hm, it should work. Could you try restarting the kernel? Commented Aug 1, 2016 at 23:09
• Flatten by itself removes all Lists. The second argument specifies which level it should remove. (e.g. 2 removes two enclosing Lists). If you put a list or a matrix in the second argument, it Flattens those levels only. Here is a good explanation on that: (119). Commented Aug 1, 2016 at 23:16

In this case, I would recommend ArrayReshape, which I think is easy to understand

Let

a = {{{{1, 2, 3}, {4, 5, 6}}}, {{{7, 8, 9}, {10, 11, 12}}}};
b = {{{1, 2, 3}, {4, 5, 6}}, {{7, 8, 9}, {10, 11, 12}}};


Now

Dimensions[b]


{2, 2, 3}

So you want a to be reshaped into a 2 x 2 x 3 array; therefore,

ArrayReshape[a, {2, 2, 3}] == b


True

### Update

ArrayReshape can easily handle complicated cases of unwanted extra levels of List wrapping, which is something Mathematica is prone to produce. In general one can use

ArrayReshape[list, DeleteCases[Dimensions[list], 1]]


to unwrap sub-lists of one element. Thus,

ArrayReshape[a, DeleteCases[Dimensions[a], 1]] == b


True

and

c = {{{{{{1}, {2}, {3}}, {{4}, {5}, {6}}}}, {{{{7}, {8}, {9}}, {{10}, {11}, {12}}}}}}
ArrayReshape[c, DeleteCases[Dimensions[c], 1]] == b


True

• You might consider addition a few of these points to Michael's answer here: (105866) Commented Aug 2, 2016 at 7:01
• @Mr.Wizard. I added a comment to the answer you cite that links to this answer. I hope that's sufficient -- I feel uncomfortable making substantive edits to the answers. of others. Commented Aug 2, 2016 at 12:58

Example

a = {{{{1, 2, 3}, {4, 5, 6}}}, {{{7, 8, 9}, {10, 11, 12}}}};
b = {{{1, 2, 3}, {4, 5, 6}}, {{7, 8, 9}, {10, 11, 12}}};

Flatten[a, 1]


Output

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

Test

Flatten[a, 1] == b


True

I use Join @@ (@@ is shorthand for Apply) most of the time but version 10 introduced Catenate which is now arguably the canonical method:

Catenate[A] === B   (* True *)


Be aware however that Catenate and Flatten unpack; this just came up in