Count

First I define (lst) which will be used to demonstrate Count.

lst = Table[Random[Integer, {0, 9}],     {3}, {2}, {2}, {2}]

{{{{7, 1}, {3, 7}}, {{9, 5}, {4, 3}}}, {{{6, 6}, {1, 6}}, {{3, 6}, {3, 3}}}, {{{9, 7}, {3, 9}}, {{1, 3}, {4, 6}}}}

The following returns 3 because lst has three elements and each has the form (_List).

Count[lst, _List]

3

The three lists found with the example from the previous cell are returned by evaluating the next input.

Part[lst, 1] Part[lst, 2] Part[lst, 3]

{{{7, 1}, {3, 7}}, {{9, 5}, {4, 3}}}

{{{6, 6}, {1, 6}}, {{3, 6}, {3, 3}}}

{{{9, 7}, {3, 9}}, {{1, 3}, {4, 6}}}

The next input counts six lists at level 2.

Count[lst, _List, {2}]

6

The six lists found with the example from the previous cell are returned by evaluating the next input.

Part[lst, 1, 1] Part[lst, 1, 2] Part[lst, 2, 1] Part[lst, 2, 2] Part[lst, 3, 1] Part[lst, 3, 2]

{{7, 1}, {3, 7}}

{{9, 5}, {4, 3}}

{{6, 6}, {1, 6}}

{{3, 6}, {3, 3}}

{{9, 7}, {3, 9}}

{{1, 3}, {4, 6}}

The next input counts ten lists at levels zero through 2.

Count[lst, _List, {0, 2}]

10

The ten lists found with the example from the previous cell are returned by evaluating the next input.

lst Part[lst, 1] Part[lst, 2] Part[lst, 3] Part[lst, 1, 1] Part[lst, 1, 2] Part[lst, 2, 1] Part[lst, 2, 2] Part[lst, 3, 1] Part[lst, 3, 2]

{{{{7, 1}, {3, 7}}, {{9, 5}, {4, 3}}}, {{{6, 6}, {1, 6}}, {{3, 6}, {3, 3}}}, {{{9, 7}, {3, 9}}, {{1, 3}, {4, 6}}}}

{{{7, 1}, {3, 7}}, {{9, 5}, {4, 3}}}

{{{6, 6}, {1, 6}}, {{3, 6}, {3, 3}}}

{{{9, 7}, {3, 9}}, {{1, 3}, {4, 6}}}

{{7, 1}, {3, 7}}

{{9, 5}, {4, 3}}

{{6, 6}, {1, 6}}

{{3, 6}, {3, 3}}

{{9, 7}, {3, 9}}

{{1, 3}, {4, 6}}

I don't provide further examples, but any combination of pattern matching constructs can be used with Count.  Nuances of pattern matching are discussed in another section.

Heads Option

Count has a Heads option with the default setting (Heads→False).  First I define (expr) which will be used to demonstrate this option.  In the first example Count ignores the (h) in h[x,y] because of the default setting for Heads.

ClearAll[h] ; expr = {h[x, y], {h, 0}, {h, 3}, {3, 4}} ; Count[expr, h, {2}]

2

When the last example is repeated using (Heads→True) the (h) in h[x,y] is accounted for.  

expr = {h[x, y], {h, 0}, {h, 3}, {3, 4}} ; Count[expr, h, {2}, HeadsTrue]

3


Created by Mathematica  (May 16, 2004)

Back to Ted’s Tricks index page