Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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.

share|improve this question
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 –  belisarius Jul 27 '12 at 22:03
add comment

1 Answer 1

up vote 7 down vote accepted

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.

share|improve this answer
2  
You nailed it. +1 –  Mr.Wizard Jul 28 '12 at 7:33
    
That works nicely, thanks –  alancalvitti Jul 28 '12 at 19:09
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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