3

Is there a function in Mathematica which removes brackets from an expression?

RemoveBrackets[ {3} ]

3

Note: inspired by @garej's answer to this question :Brackets around each item in matrix

  • further edits/comments/answers welcome
Conor
  • 7,449
  • 1
  • 22
  • 46

2 Answers2

10

This question is closely related to:

If you wish to strip the brackets from a single expression in a nontrivial case please consider Delete as described in my answer to the second referenced question above.

  • Unlike using Apply (e.g. # & @@ {1} or Sequence @@ {1}) it does not first replace List with something else which means it behaves better inside held expressions.

  • Unlike Part, First, etc. it works equally well with multiple arguments, allowing us to strip the {} from e.g. HoldComplete[{1, 2, 3}] using // Delete[{1, 0}].

If you wish to strip brackets throughout an expression you can use the methods from the first linked question, being mindful of the tradeoff between brevity and efficiency.

expr = {{0, {{1, 2}}, {3}}, {4}};

expr //. {x_} :> x
{{0, {1, 2}, 3}, 4}
Replace[expr, {x_} :> x, {0, -2}]
{{0, {1, 2}, 3}, 4}
Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
5

I learned from @Kuba:

First[{3}]

3

#& @@{3}

3

these do this task even more generally than I imagined.

given any Atomic expressions wrapped with any function >> the FullForm of almost everthing in Mathematica

ArbitraryHead[expr1, expr2 ]

First[ArbitraryHead[expr1, expr2]]

expr1

#&@@ArbitraryHead[expr1,expr2]

expr1



here are specific examples:


First[(1/a^2)]

a

why?:

 (1/a^2)//FullForm

Power[a, -2]


First[List[3]]

3

P.S. I feel this community is building a tall cathedral of knowledge. I'm doing my little bit of brickwork.



{3}[[1]]

3


##& @@{3}

3


Seqence[{3}]

Sequence[3]

Conor
  • 7,449
  • 1
  • 22
  • 46