Count¶
Status: Stable
documented, exercised by the test suite and/or worked examples, with no known limitations recorded.
Description¶
Count[list, pattern] gives the number of elements in list that match pattern.
Count[expr, pattern, levelspec] gives the total number of subexpressions matching pattern that appear at the levels in expr specified by levelspec.
Count[pattern] represents an operator form of Count that can be applied to an expression.
Examples¶
No verified examples yet for this function.
Implementation notes¶
Algorithm. builtin_count (src/patterns.c) tallies the subexpressions matching a pattern. Level-spec (default {1,1} — immediate elements only), the Heads -> True|False option, and the argument shapes mirror Cases. The worker do_count_at_level recurses depth-first into the head (when heads) and every argument, and at each in-range node calls match(e, pattern, env) from src/match.c, incrementing a size_t counter on success; level membership for negative specs is resolved via get_expr_depth_patterns. Unlike Cases/Position it stores nothing and has no result limit — it just returns the final count as an EXPR_INTEGER. Count[pat] with one argument returns the operator form Function[Count[#1, pat]].
Data structures. A single size_t accumulator; one MatchEnv per node tested. No results buffer.
- Uses standard level specifications, defaulting to level
{1}. - Option
Heads -> Trueevaluates heads of expressions. - Effectively returns the length of the list generated by
Casesfor the same arguments. p:def:Optional[p, def], matchesp, but if omitted defaults todef.x_.:Optional[Pattern[x, _]], matchesx_, but if omitted defaults to globally specifiedDefaultvalues.p..:Repeated[p], matches a sequence of one or more expressions, each matchingp.p...:RepeatedNull[p], matches a sequence of zero or more expressions, each matchingp.Repeated[p, max],Repeated[p, {min, max}],Repeated[p, {n}]: match sequences of length bounded bymaxor{min, max}. Equivalent properties exist forRepeatedNull.
Attributes: Protected.
Implementation status¶
Stable — documented, exercised by the test suite and/or worked examples, with no known limitations recorded.
References¶
- Source:
src/patterns.c - Specification:
docs/spec/builtins/pattern-matching.md
Notes & additional examples¶
Worked examples¶
Notes¶
The second argument is a pattern, so Count[list, _?EvenQ] counts elements satisfying a predicate, not just literal matches. A level specification such as Infinity makes Count recurse into subexpressions, so it counts every matching leaf at any depth — here Count[Range[100], _?PrimeQ] recovers the prime-counting value 25, and the last example tallies how many decimal digits of 2^100 exceed 5.