Function Repository Resource:

DropTrailingWhile

Source Notebook

Drop elements at the end of a list so long as a criterion is fulfilled

Contributed by: Sander Huisman

ResourceFunction["DropTrailingWhile"][list,crit]

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

ResourceFunction["DropTrailingWhile"][crit]

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

Details and Options

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

Examples

Basic Examples (2) 

Drop elements from the back that are odd:

In[1]:=
ResourceFunction["DropTrailingWhile"][{2, 4, 6, 1, 5, 3}, OddQ]
Out[1]=

Use a pure function to drop elements from the back while they are larger than 100:

In[2]:=
ResourceFunction[
 "DropTrailingWhile"][{1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,
   377}, # > 100 &]
Out[2]=

Scope (2) 

Elements of the list can be any expression:

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

Create an operator of DropTrailingWhile that drops trailing even numbers:

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

Use the operator:

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

Generalizations & Extensions (2) 

Use on an expression with head f:

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

DropTrailingWhile also works on SparseArray:

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

Applications (1) 

Drop trailing zeros:

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

Properties and Relations (2) 

DropTrailingWhile is equivalent to a combination of Drop, Reverse and LengthWhile:

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

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

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

Possible Issues (1) 

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

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

Publisher

SHuisman

Requirements

Wolfram Language 11.3 (March 2018) or above

Version History

  • 1.0.0 – 26 April 2019

Related Resources

License Information