4
$\begingroup$

I would like to reduce the number of brackets in a list for nested lists containing 1 sublist. For instance {{1,2,3}} should become {1,2,3}

However, {{1,2,3},{4,5}} should stay the same.

I used:

DropLevel[x_] := Level[x, {-1}] /; Dimensions[x][[1]] == 1

Which gives an error on {{1,2,3},{4,5}} but works on {{1,2,3}}

Dimensions[x][[1]]==1 does work as a test for checking whether a list has two sublists or only 1.

Am I missing something about the way /; functions?

$\endgroup$
7
$\begingroup$

You can use ReplaceAll with the replacement rule {{x__}} :> {x}:

stripDoubleBraces = # /. {{x__}} :> {x} &

stripDoubleBraces @ {{1, 2, 3}}

{1, 2, 3}

stripDoubleBraces @ {{1, 2, 3}, {4, 5}}

{{1, 2, 3},{4,5}}

If you need to the stripping work with arbitrarily deep nesting, you can replace ReplaceAll with ReplaceRepeated:

 {{1}, {{{{{{{5}}}}}}}} //. {{x__}} :> {x}

{{1}, {5}}

| improve this answer | |
$\endgroup$
  • $\begingroup$ Thanks again! I will dig into that book soon. Pattern matching is so cool in this language. $\endgroup$ – Mike Jun 21 '19 at 22:36

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.