I am trying to define a substitution that gives 1 for odd numbers and 0 for even numbers. My guess was (in a particular example)

{0, 1, 2, 3, 4, 5, 6} /. N_Integer -> If[EvenQ[N], 0, 1]

But the output is {1,1,1,1,1,1,1}. The problem is in EvenQ[] which is acting on a symbol, but I specified before that it should be applied only to integers, so I do not understand why it does not work.

Where is the problem? Does it have something to do with ->?


closed as off-topic by Bob Hanlon, Henrik Schumacher, José Antonio Díaz Navas, J. M. is away Oct 21 '18 at 10:39

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "This question arises due to a simple mistake such as a trivial syntax error, incorrect capitalization, spelling mistake, or other typographical error and is unlikely to help any future visitors, or else it is easily found in the documentation." – Bob Hanlon, Henrik Schumacher, José Antonio Díaz Navas, J. M. is away
If this question can be reworded to fit the rules in the help center, please edit the question.

  • 14
    $\begingroup$ Yes. Use :> instead of ->. But then, why not use Mod[list, 2]? $\endgroup$ – J. M. is away Oct 18 '18 at 13:25

In case speed matters Mod suggested by J.M. in comments is orders of magnitude faster than ReplaceAll and Boole:

input = RandomInteger[10^6, 10^6];
First[RepeatedTiming[res0 = input /. n_Integer :> If[EvenQ[n], 0, 1];]]


First[RepeatedTiming[ res1 = Boole@OddQ@input; ]]


First[RepeatedTiming[res2 =  With[{True = 1, False = 0}, Evaluate@OddQ[input]]; ]]


First[RepeatedTiming[ res3 = Mod[input, 2];]] 


res0 == res1 == res2 == res3
> True

where the trick in res2 is from this answer by Mr.Wizard.

  • $\begingroup$ Nice trick! (But it's disappointing.) $\endgroup$ – Alan Oct 19 '18 at 14:03

See JM's comment. The following points in a somewhat more general direction for some queries.

Boole@OddQ@Range[0, 6]
  • 3
    $\begingroup$ It should be Boole@OddQ@Range[0, 6] $\endgroup$ – rmw Oct 18 '18 at 21:01

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