Count

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.

Details and Options

  • The first argument to Count need not have head List.
  • When used on an Association, Count tests only the values of elements, not their keys.
  • Count uses standard level specifications:
  • nlevels 1 through n
    Infinitylevels 1 through Infinity
    {n}level n only
    {n1,n2}levels n1 through n2
  • The default value for levelspec in Count is {1}.
  • A positive level n consists of all parts of expr specified by n indices.
  • A negative level -n consists of all parts of expr with depth n.
  • Level -1 consists of numbers, symbols and other objects that do not have subparts.
  • Level 0 corresponds to the whole expression.
  • With the option setting Heads->True, Count looks at heads of expressions and their parts.
  • Count[pattern][expr] is equivalent to Count[expr,pattern].

Examples

open allclose all

Basic Examples  (4)

Count how many times b occurs:

Count powers of x in an Association:

Count powers of x on all levels:

Count symbols:

Scope  (5)

Count works with patterns:

Count the number of elements not matching b:

Count occurrences of b down to level 2:

Count occurrences at level 2 only:

Count all numeric expressions appearing as part of a larger expression:

A numeric level specification does not include level zero:

Use a two-element list to explicitly include level zero:

Generalizations & Extensions  (1)

Count works with any head, not just List:

Options  (1)

Heads  (1)

By default, expressions appearing as heads are not counted:

Use the option Heads->True to include them:

Applications  (3)

Count the total number of symbols in an expression:

Count the total number of elements greater than 0.5:

Count the number of rows whose first element is 1:

Properties & Relations  (4)

Count returns the length of the result given by Cases:

Count returns the length of the result given by Position:

A count at level {0} is effectively a numericized version of MatchQ:

For most expressions, LeafCount equals the count matching Blank[] at level {-1}:

Count treats Rational and Complex as atoms:

LeafCount counts Rational and Complex numbers using their FullForm:

Possible Issues  (1)

Count looks for matches based on patterns, which may not be the same as numerical equality:

Write a pattern using Condition to force searching based on numerical equality:

Introduced in 1988
 (1.0)
 |
Updated in 2014
 (10.0)