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?


2 Answers 2


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)
  • 1
    $\begingroup$ 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) $\endgroup$
    – Mr.Wizard
    Jan 9, 2013 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.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.