Cases

Cases[{e1,e2,},pattern]
gives a list of the that match the pattern.

Cases[{e1,},patternrhs]
gives a list of the values of rhs corresponding to the that match the pattern.

Cases[expr,pattern,levelspec]
gives a list of all parts of expr on levels specified by levelspec that match the pattern.

Cases[expr,patternrhs,levelspec]
gives the values of rhs that match the pattern.

Cases[expr,pattern,levelspec,n]
gives the first n parts in expr that match the pattern.

Cases[pattern]
represents an operator form of Cases that can be applied to an expression.

Details and OptionsDetails and Options

  • The first argument to Cases need not have head List.
  • When used on an Association, Cases picks out elements according to their values.
  • Cases[expr,pattern:>rhs] evaluates rhs only when the pattern is found.
  • Cases[pattern][list] is equivalent to Cases[list,pattern].
  • Cases uses standard level specifications:
  • nlevels through n
    Infinitylevels through Infinity
    {n}level n only
    {n1,n2}levels through
  • The default value for levelspec in Cases is .
  • 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 consists of numbers, symbols and other objects that do not have subparts.
  • Level corresponds to the whole expression.
  • With the option setting Heads->True, Cases looks at heads of expressions, and their parts.
  • Cases traverses the parts of expr in a depth-first order, with leaves visited before roots.

ExamplesExamplesopen allclose all

Basic Examples  (4)Basic Examples  (4)

Find cases that explicitly match integers:

In[1]:=
Click for copyable input
Out[1]=

Find cases that do not match integers:

In[2]:=
Click for copyable input
Out[2]=

Return the from inside each matched:

In[1]:=
Click for copyable input
Out[1]=

Use the operator form of Cases:

In[1]:=
Click for copyable input
Out[1]=

Pick elements from an Association:

In[1]:=
Click for copyable input
Out[1]=
Introduced in 1988
(1.0)
| Updated in 2014
(10.0)