Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
share|improve this question
1  
related: 21174 – Kuba Feb 10 at 9:09
up vote 8 down vote accepted

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}
share|improve this answer

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]

share|improve this answer
1  
Don't forget Part and Sequence. – Sjoerd C. de Vries Feb 10 at 8:47
1  
I agree, I've always been partial to using a[[1]] instead of First[a] – JasonB Feb 10 at 8:50
1  
Seqence[{3}] evaluates to Seqence[{3}] -- did you forget something? – Mr.Wizard Feb 10 at 9:58
2  
FYI: Head is a defined function with a specific purpose, and best not used as an arbitrary inert head in an example. – Mr.Wizard Feb 10 at 10:15

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.