Wolfram Research

Function Repository Resource:

DropWhile

Source Notebook

Drop elements of a list while a criterion remains true

Contributed by: Sander Huisman

ResourceFunction["DropWhile"][list,crit]

drops elements ei from the beginning of list, continuing so long as crit[ei] is True.

ResourceFunction["DropWhile"][crit]

represents an operator form of ResourceFunction["DropWhile"] that can be applied to expressions.

Details and Options

ResourceFunction["DropWhile"] can be used on an object with any head, not necessarily List.

Examples

Basic Examples

Drop elements while they are even:

In[1]:=
ResourceFunction["DropWhile"][{2, 4, 6, 1, 2, 3}, EvenQ]
Out[1]=

Use a pure function to drop elements while they are all below 10:

In[2]:=
ResourceFunction[
 "DropWhile"][{1, 1, 2, 3, 5, 8, 13, 21, 34, 55}, # < 10 &]
Out[2]=

Scope

Elements of the list can be any expression:

In[3]:=
ResourceFunction["DropWhile"][{a, Pi, 3, 2, {1, 2, 3}, {a, b}, 10}, Head[#] =!= List &]
Out[3]=

Create an operator of DropWhile that drops leading even numbers:

In[4]:=
operator = ResourceFunction["DropWhile"][EvenQ]
Out[4]=

Use the operator:

In[5]:=
operator[{2, 4, 6, 1, 2, 3}]
Out[5]=

Generalizations & Extensions

Use on an expression with head f:

In[6]:=
ResourceFunction["DropWhile"][f[0, 4, 2, 8, 1, 3, 8, 13, 21], EvenQ]
Out[6]=

DropWhile also works on SparseArray:

In[7]:=
ResourceFunction["DropWhile"][
 SparseArray[{{1} -> 10, {2} -> 20, {3} -> 30, {4} -> 40}], LessThan[25]]
Out[7]=

Applications

Drop leading zeros:

In[8]:=
ResourceFunction[
 "DropWhile"][{0, 0, 0, 0, 0, 0, 13.4, 15.7, 11.3, 9.3, 2.7}, EqualTo[0.]]
Out[8]=

Properties and Relations

DropWhile is equivalent to a combination of Drop and LengthWhile:

In[9]:=
data = {1, 1, 2, 3, 5, 8, 13, 21}
Out[9]=
In[10]:=
ResourceFunction["DropWhile"][data, # < 7 &]
Out[10]=
In[11]:=
Drop[data, LengthWhile[data, # < 7 &]]
Out[11]=

DropWhile gives an empty list if crit[ei] is True for all elements:

In[12]:=
ResourceFunction["DropWhile"][{1, 1, 2, 3, 5, 8, 13, 21}, NumberQ]
Out[12]=

Combining the results of TakeWhile and DropWhile gives the original list:

In[13]:=
data = {1, -1, 2, a, 3, b, 5, 8, 13, 21};
TakeWhile[data, # < 7 &]~Join~
 ResourceFunction["DropWhile"][data, # < 7 &]
Out[14]=

Possible Issues

The list terminates for any value of crit[ei] that is not True:

In[15]:=
ResourceFunction["DropWhile"][{E, 8, a, b, 20, 1.4}, If[NumericQ[#], True, #] &]
Out[15]=

Requirements

Wolfram Language 11.3 (March 2018) or above

Resource History

See Also

License Information