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

if I execute the following command in Mathematica:

{a,a^2,a^3}/.a^(n_:1)->b^(2 n)

Mathematica returns:


but if I enter:

{a,a^2,a^3}/.a_^(n_:1)->b^(2 n)

Mathematica only returns:


Without the default value for n, Mathematica returns in both instances (a & a_):


Could someone explain why the different behavior?

share|improve this question

First try looking at:

 {a, a^12, a^13} /. a_^(n_: 1) -> b^(2 n)


You'll notice that it's not the case that it's just returning just one of the elements. What is' doing is actually replacing the whole list. This happens because anything is equal to itself to the power of 1.

 MatchQ[{4, Plot, Sin}, a_^(n_: 1)]

So what happens is that when you use a blank pattern _ you can match anything, and the first thing encountered is the entire list. For this particular case you can solve this by making sure you are only matching symbols and not expressions, and by checking that you aren't replacing your head of List:

 {a, a^12, a^13} /. (a_Symbol /; a =!= List)^(n_: 1) -> b^(2 n)
share|improve this answer
I beat you by a hair. +1 for providing an alternative. Another is: {a, a^2, a^3} /. a : Except[List | _List]^(n_: 1) :> b^(2 n) – Mr.Wizard Jan 9 '13 at 10:42

Your problem is simply that your entire left hand expression matches the pattern:

MatchQ[{a, a^2, a^3}, a_^(n_: 1)]

You can avoid this match is a variety of ways such as more restrictive patterns but perhaps the best is a level restriction. (We can use the _. form of Optional because the effective default is already 1.)

 {a, a^2, a^3},
 a_^n_. :> b^(2 n),
{b^2, b^4, b^6}


# /. a_^n_. :> b^(2 n) & /@ {a, a^2, a^3}
{b^2, b^4, b^6}

Notice that in all cases I changed -> to :>; the latter (RuleDelayed) should be used to correctly localize n.

share|improve this answer

Your Answer


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.