Function Repository Resource:

DeleteAdjacentDuplicates

Source Notebook

Delete adjacent duplicates from a list

Contributed by: Richard Hennigan (Wolfram Research)

ResourceFunction["DeleteAdjacentDuplicates"][list]

deletes adjacent duplicate items from list.

ResourceFunction["DeleteAdjacentDuplicates"][list,test]

applies test to pairs of adjacent elements in list to determine if they should be considered duplicates.

Details and Options

ResourceFunction["DeleteAdjacentDuplicates"] also works on associations, removing entries whose values duplicate those coming just before them in the association.
ResourceFunction["DeleteAdjacentDuplicates"] never reorders elements, but only removes them.
ResourceFunction["DeleteAdjacentDuplicates"][list] is equivalent to ResourceFunction["DeleteAdjacentDuplicates"][list,SameQ].

Examples

Basic Examples (2) 

Delete adjacent duplicated elements:

In[1]:=
ResourceFunction[
 "DeleteAdjacentDuplicates"][{0, 0, 0, 1, 1, 2, 0, 0, 0, 0}]
Out[1]=

Delete elements whose values duplicate those just before them in the association:

In[2]:=
ResourceFunction[
 "DeleteAdjacentDuplicates"][<|a -> 1, b -> 1, c -> 2, d -> 2, e -> 1|>]
Out[2]=

Scope (4) 

Delete elements unless they are larger than the preceding ones:

In[3]:=
ResourceFunction[
 "DeleteAdjacentDuplicates"][{1, 3, 5, 4, 3, 4, 1, 9, 9, 7, 8}, Greater]
Out[3]=

Delete adjacent duplicates from an association without evaluating any of the keys or values:

In[4]:=
assoc = Block[{Echo}, <|Echo[a] -> 1, b -> 1, c -> Echo[2], d -> Echo[2], e -> 1|>]
Out[4]=
In[5]:=
ResourceFunction["DeleteAdjacentDuplicates"][assoc]
Out[5]=

They will still evaluate if unpacked from the association:

In[6]:=
Normal[%]
Out[6]=

Use Unevaluated to delete adjacent duplicates before they can evaluate:

In[7]:=
ResourceFunction["DeleteAdjacentDuplicates"][
 Unevaluated[{Echo[1], Echo[1], Echo[1], Echo[2], Echo[2]}]]
Out[7]=

The first argument can be any nonatomic expression:

In[8]:=
ResourceFunction["DeleteAdjacentDuplicates"][
 f[x, x, y, y, y, x, x, y, z]]
Out[8]=

Properties and Relations (2) 

DeleteAdjacentDuplicates is similar to taking the first of each item from Split:

In[9]:=
list = RandomInteger[2, 20]
Out[9]=
In[10]:=
Split[list][[All, 1]]
Out[10]=
In[11]:=
ResourceFunction["DeleteAdjacentDuplicates"][list]
Out[11]=

Delete sublists that have the same total:

In[12]:=
list = {{1, 2}, {0, 3}, {1, 1}, {2, 0}, {2, 1}}
Out[12]=
In[13]:=
ResourceFunction["DeleteAdjacentDuplicates"][list, Total[#1] == Total[#2] &]
Out[13]=

SplitBy can be used to achieve the same result:

In[14]:=
SplitBy[list, Total][[All, 1]]
Out[14]=

Version History

  • 1.0.0 – 22 May 2019

Related Resources

License Information