# How to efficiently Flatten nested lists while preserving select levels? [duplicate]

I have lists of sets of variables, some in nested sub-lists:

t = {{1, 2}, {3, 4}, {{5, 6}, {7, 8, 9}}}


I need to flatten this list in place but preserve the sets. Flatten[t,1] does the opposite of what I want:

t = Flatten[t,1]


(* {1, 2, 3, 4, {5, 6}, {7, 8, 9}} *)

The following code does what I want if there's only one level of flattening to do. However, it requires a lot of copying, and I'm working with list of >10^5 elements, so I'd like to do this more efficiently if possible.

t = Reap[Do[If[Length[t[[i, 1]]] == 0, Sow[t[[i]]], Do[Sow[t[[i, j]]], {j, 1, Length[t[[i]]]}]], {i, 1, Length[t]}]][[2, 1]]

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


Is there a more efficient way?

• Possible duplicate of How can I Flatten this List with Inner List of Lists? – Quantum_Oli Mar 10 '17 at 13:16
• @Quantum_Oli Disturbingly I had no memory of answering the question to which you linked, though I seem to have nearly reproduced that answer here. – Mr.Wizard Mar 10 '17 at 13:26
• @Mr.Wizard Heh, I happened upon your elegant Level solution only a few days ago so it was still fresh in my mind! – Quantum_Oli Mar 10 '17 at 14:40

If your list elements are atomic Level is fast and concise:

t = {{1, 2}, {3, 4}, {{5, 6}, {7, 8, 9}}};

Level[t, {-2}]

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


If you have something more complicated Cases can help:

t2 = {{a[1], a[2]}, {3, 4}, {{x[5], x[6]}, {7, 8, 9}}};

Cases[t2, {Except[_List], ___}, -2]

{{a[1], a[2]}, {3, 4}, {x[5], x[6]}, {7, 8, 9}}

• That seems to do exactly what I wanted, treat the lowest level lists as atomic. I looked at the Level[] documentation after you posted this, but I don't understand what the {} in the levelspec is doing. Should I make a separate Question of that? – Jerry Guern Mar 10 '17 at 1:44
• @JerryGuern No, there is already a question about that; if you find it a useful topic please vote for the Question; it is unfairly down-voted IMO: mathematica.stackexchange.com/q/29750/121 -- edit and if you feel my answer does not sufficiently address {} tell me and I shall try to improve it! – Mr.Wizard Mar 10 '17 at 1:46
• Done. I upvoted that question and edited its title to be more specific. – Jerry Guern Mar 10 '17 at 2:04