Is there a built in method to de-list singleton expressions, like this rule-based solution:

expr_ :>  If[Length[expr] == 1, First@expr, expr]

In data analysis, this comes in handy to normalize the output of Cases, since a single exact match will be wrapped in a list, but wrapping that in First would break no-match cases and non-singleton lists.

  • 1
    $\begingroup$ If you return a variable Head from an expression (Atom or List could be in this case), you will have troubles for using the result later. Before using Map, for example you will have to test if applicable $\endgroup$ Jul 27 '12 at 22:03

You can use a simple replacement rule like in the following example:

list = {a, {b}, {c, d}, {e, {f, g}}, {{h}}};
list /. _[x_] :> x
(* {a, b, {c, d}, {e, {f, g}}, {h}} *)

This will strip a layer from expressions with length 1, for all heads. You can restrict it further to act only on List, if that's what you desire.

  • 2
    $\begingroup$ You nailed it. +1 $\endgroup$
    – Mr.Wizard
    Jul 28 '12 at 7:33
  • $\begingroup$ That works nicely, thanks $\endgroup$ Jul 28 '12 at 19:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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