# Explanation for RandomChoice list increment behavior [duplicate]

Why does this code produce a number close to 1000 but not exactly 1000?

a = {0, 0};
Do[a[[RandomChoice[{1, 2}]]]++, 1000]
Total[a]


Moreover the number seems to be random within some range.

• related: 2300
– Kuba
Jan 12, 2017 at 12:36
• @Kuba I had forgotten about that old question. Amusing that a search turned that up but not the newer one. I remember that at that time I was mightily confused until I figured it out so I posted the question to get others to consider the problem. Jan 12, 2017 at 13:02
• @Mr.Wizard I forced myself to answer to be sure I got that :) Wasn't obvious the more that without TraceInternal one will not see the second RandomChoice.
– Kuba
Jan 12, 2017 at 13:03

Because Increment is HoldAll and RandomChoice evaluates twice. First time to get the value to increment and the second time to pick the index that should be affected.

If both choices match then we are fine, otherwise we are speeding up or slowing down a little. E.g.: a = {3,4}, first RandomChoice is 1 and the second 2, then we take 3+1 and assign it in the second position which was 4 too. No change here. Reversely we would have 4+1 assigned for 3 so increment of 2!

You can use Trace

Trace[
a[[RandomChoice[{1, 2}]]]++,
TraceInternal -> True
] // Column


or manually check it:

a = {0, 0}
a[[Echo@RandomChoice[{1, 2}]]]++;
a


>>1

>>2

{0,1}

Twice indeed. (use (Print[#];#)& for pre V11).

To avoid that assign RandomChoice result somewhere (var=RandomChoice[...]) or e.g:

a = {0, 0};
Do[ a[[#]]++ &@RandomChoice[{1, 2}], 100]
Total[a]


100

• Kuba, I marked this question as a duplicate. Please let me know if you disagree. Jan 12, 2017 at 12:55
• @Mr.Wizard I don't :) I failed to find it though I wasn't sure if it was an exact duplicate.
– Kuba
Jan 12, 2017 at 12:56