# Module counting number of $1$'s in a vector

I wrote a module which hopes to count the number of $$1$$'s in a given vector

mycount[v_]:=Module[{v0=v},s=0;Do[If[v0[[i]]=1,s=s+1],{i,1,Length[v0]}];s]


However, no matter how I change it around, it returns the number $$0$$ for the example vector {1,1,1,2} I used, can someone point out what is wrong becauuse I cannot see it?

• mycount[v_] := Module[{v0 = v, s = 0}, Do[If[v0[[i]] == 1, s = s + 1], {i, 1, Length[v0]}]; s]
– Syed
Oct 18, 2021 at 20:25
• Please show a complete MWE including the call itself. btw, there is a function called Count in Mathematica already. Oct 18, 2021 at 20:26
• @Syed Thank you so much! Oct 18, 2021 at 20:33
• @Nasser Nvm, I already solved it thanks to the comment above. I knew of the Count function, I was just practising creating modules and doing loops. Thanks anyway! Oct 18, 2021 at 20:35
• Count[{1, 1, 1, 2}, 1] would count 1s. I think you should look at the book written by the inventor himself for beginners.
– Syed
Oct 18, 2021 at 20:35

Here's a faster alternative that uses vectorized operations:

mycount2[v_] := Length[v] - Total[Unitize[v - 1]]


Compare (with v0[[i]] = 1 changed to v0[[i]] == 1):

list = RandomInteger[{1, 3}, 10^6];

mycount[list] // AbsoluteTiming

{0.680935, 333888}

mycount2[list] // AbsoluteTiming

{0.012579, 333888}


And a built in function:

Count[list, 1] // AbsoluteTiming

{0.033939, 333888}

• Interesting that the user-defined mycount2 outperforms built-in Count here. Oct 19, 2021 at 15:04