4
$\begingroup$

This question already has an answer here:

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?

$\endgroup$

marked as duplicate by Quantum_Oli, Mr.Wizard list-manipulation Mar 10 '17 at 13:26

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 1
    $\begingroup$ Possible duplicate of How can I Flatten this List with Inner List of Lists? $\endgroup$ – Quantum_Oli Mar 10 '17 at 13:16
  • $\begingroup$ @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. $\endgroup$ – Mr.Wizard Mar 10 '17 at 13:26
  • $\begingroup$ @Mr.Wizard Heh, I happened upon your elegant Level solution only a few days ago so it was still fresh in my mind! $\endgroup$ – Quantum_Oli Mar 10 '17 at 14:40
4
$\begingroup$

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}}
$\endgroup$
  • $\begingroup$ 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? $\endgroup$ – Jerry Guern Mar 10 '17 at 1:44
  • $\begingroup$ @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! $\endgroup$ – Mr.Wizard Mar 10 '17 at 1:46
  • $\begingroup$ Done. I upvoted that question and edited its title to be more specific. $\endgroup$ – Jerry Guern Mar 10 '17 at 2:04

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