I would like to get the number of different values found in a List.
For example:
The output for the List a={1,2,3,4,5}
would be 5 whereas it would be 2 for b={1,1,1,2,2}
.
Just for amusement, all the following commands also give the desired result:
Length@Gather@l
Length@Union@l
Length@Tally@l
Count[BinCounts@l, Except@0]
Count[BinLists@l, Except@{}]
Length@Split@Sort@l
Length@GatherBy[l, # &]
Length@Split@SortBy[l, # &]
And many more, of course.
Edit
Here is a little timing experiment (not serious)
l = RandomInteger[{1, 10^2}, 10^7];
t2[x_] := {Timing[x], ToString[HoldForm@x]};
SetAttributes[t2, HoldAll]
Grid[Reverse /@
{t2[Length@DeleteDuplicates[l]],
t2[Length@Tally[l]],
t2[Length@Gather[l]],
t2[Count[BinCounts[l], Except@0]],
t2[Length@Union[l]],
t2[Length@Split@Sort@l],
t2[Count[BinLists[l], Except@0]]},
Frame -> All]
BTW: Note the difference between BinLists[ ]
and BinCounts[ ]
Edit
A more detailed view of DeleteDuplicates
vs Tally
t = Timing;
ListLinePlot@Transpose@
Table[l = RandomInteger[{1, 10^i}, 10^7];
{Log@First@t@Length@DeleteDuplicates@l,
Log@First@t@Length@Tally@l},
{i, Range[7]}]
Beware! Log Plot!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With