DeleteCases

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

expr = {1, 1.2, {2, 1.3, {3, 1.4}, {4, {1.5}}}} ;

The first example deletes all real numbers at level 1 and the only one at that level was 1.2.  Recall 1, 2, 3, ... have the head Integer not Real.

DeleteCases[expr, _Real]

{1, {2, 1.3, {3, 1.4}, {4, {1.5}}}}

The next example deletes all Real numbers at levels 1 through 3.  The integers deleted were 1.2, 1.3, 1.4.  More discussion on level specification is given in another section.

DeleteCases[expr, _Real, {1, 3}]

{1, {2, {3}, {4, {1.5}}}}

The next example deletes Real numbers at level 3.  The only Real number at level 3 was 1.4.

DeleteCases[expr, _Real, {3}]

{1, 1.2, {2, 1.3, {3}, {4, {1.5}}}}

The next example deletes all Real numbers at any level.

DeleteCases[expr, _Real, {0, -1}]

{1, {2, {3}, {4, {}}}}

In the next example I give an alternate way to delete Real numbers at any level.

expr/._RealSequence[]

{1, {2, {3}, {4, {}}}}

In the next example I give an alternate way to delete Real numbers at levels 1 through 3.

Replace[expr, _RealSequence[], {1, 3}]

{1, {2, {3}, {4, {1.5}}}}

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

DeleteCases has a Heads option with the default setting (Heads→False).  First I define (expr) which will be used to demonstrate this option.

ClearAll[h, x, y] ; expr = {h[x, y], {6, h, 7}} ;

In the next cell DeleteCases ignores the (h) in h[x,y] because of the default setting for Heads.

DeleteCases[expr, h, {0, -1}, HeadsFalse]

{h[x, y], {6, 7}}

When the previous example is repeated with the option (Heads→True) the (h) in h[x,y] is deleted.

DeleteCases[expr, h, {0, -1}, HeadsTrue]

{x, y, {6, 7}}

Below I give alternate methods of getting the same results as the last two examples.

Replace[expr, hSequence[], {0, -1}]

{h[x, y], {6, 7}}

expr/.h[args__] args/.hSequence[]

{x, y, {6, 7}}


Created by Mathematica  (May 16, 2004)

Back to Ted’s Tricks index page