# Substituting 0 for even and 1 for odd natural numbers using EvenQ[] [closed]

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 ->?

• Yes. Use :> instead of ->. But then, why not use Mod[list, 2]? Oct 18, 2018 at 13:25

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

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


0.999

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


.0226

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


0.048

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


0.00722

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


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

• Nice trick! (But it's disappointing.)
– Alan
Oct 19, 2018 at 14:03

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

Boole@OddQ@Range[0, 6]

• It should be Boole@OddQ@Range[0, 6]
– rmw
Oct 18, 2018 at 21:01