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

This question already has an answer here:

I am having some difficulties with the ReplaceAll function. When I write:

{1, 2, 3, 4, 5} /. x_?OddQ -> x^2

I expect:


But if I write:

x = 1;
{1, 2, 3, 4, 5} /. x_?OddQ -> x^2

I have:


How can I avoid this? I mean, even using:

x = 1;
Module[{x},{1, 2, 3, 4, 5} /. x_?OddQ -> x^2]

The output still:


Thanks in advance!

Edit: Thanks again! I never quite understood this RuleDelayed.

share|improve this question

marked as duplicate by Mr.Wizard Jul 19 '13 at 0:03

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

Use RuleDelayed (:>), instead of Rule (->). – Leonid Shifrin Jul 18 '13 at 14:03
I discussed this issue in my book, here and in the section directly following it. I also seem to remember that this was nicely discussed in the documentation for Rule and RuleDelayed, so you may want to check that out. – Leonid Shifrin Jul 18 '13 at 14:18
Also related: (25652) – Mr.Wizard Jul 19 '13 at 0:03

Just use :> (that is RuleDelayed) instead of -> (Rule). Indeed, the Rule will evaluate the right-hand side of the rule immediately, that means it will use the x = 1 value before to define the rule itself. On the other hand, RuleDelayed will evaluate the right-hand side only after the rule itself is created and then the x is that inside the rule and not the Global one.

x = 1;
{1, 2, 3, 4, 5} /. x_?OddQ :> x^2
{1, 2, 9, 4, 25}
share|improve this answer

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