8

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.

rm -rf
  • 88,781
  • 21
  • 293
  • 472
alancalvitti
  • 15,143
  • 3
  • 27
  • 92
  • 1
    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 – Dr. belisarius Jul 27 '12 at 22:03

1 Answers1

9

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.

rm -rf
  • 88,781
  • 21
  • 293
  • 472