3
$\begingroup$

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
$\endgroup$
1
  • 1
    $\begingroup$ related: 21174 $\endgroup$ Commented Feb 10, 2016 at 9:09

2 Answers 2

10
$\begingroup$

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} 
$\endgroup$
5
$\begingroup$

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]

$\endgroup$
4
  • 1
    $\begingroup$ Don't forget Part and Sequence. $\endgroup$ Commented Feb 10, 2016 at 8:47
  • 1
    $\begingroup$ I agree, I've always been partial to using a[[1]] instead of First[a] $\endgroup$ Commented Feb 10, 2016 at 8:50
  • 2
    $\begingroup$ Seqence[{3}] evaluates to Seqence[{3}] -- did you forget something? $\endgroup$ Commented Feb 10, 2016 at 9:58
  • 2
    $\begingroup$ FYI: Head is a defined function with a specific purpose, and best not used as an arbitrary inert head in an example. $\endgroup$ Commented Feb 10, 2016 at 10:15

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.