Function Repository Resource:

UnsortedComplement

Source Notebook

Delete the elements of some lists from a list x without changing either the order of x or the multiplicities of its elements

Contributed by: George Beck

ResourceFunction["UnsortedComplement"][list, del1,del2, ]

deletes from listany occurrence of an element of the del1,del2, without otherwise changing list.

Details and Options

ResourceFunction["UnsortedComplement"] differs from Complement, which deletes but also reduces the multiplicity of each element to one and sorts.
ResourceFunction["UnsortedComplement"] accepts SameTest as an option.

Examples

Basic Examples (1) 

Delete specified elements from a List:

In[1]:=
ResourceFunction["UnsortedComplement"][{3, 3, 2, 1}, {2}]
Out[1]=

Scope (1) 

Deleting with several lists is equivalent to deleting with their Join:

In[2]:=
ResourceFunction[
 "UnsortedComplement"][{4, 4, 4, 4, 3, 3, 3, 2, 2, 1}, {3}, {2}]
Out[2]=
In[3]:=
ResourceFunction["UnsortedComplement"][{4, 4, 4, 4, 3, 3, 3, 2, 2, 1},
  Join[{3}, {2}]]
Out[3]=

Options (2) 

Use equivalence classes based on absolute value:

In[4]:=
ResourceFunction[
 "UnsortedComplement"][{2, -2, 1, 3, 5, 3}, {2, 1, -2, -1}, SameTest -> (Abs[#1] == Abs[#2] &)]
Out[4]=

This considers elements the same if they are identical modulo 3:

In[5]:=
ResourceFunction["UnsortedComplement"][Range[15], {2}, SameTest -> (Mod[#1, 3] == Mod[#2, 3] &)]
Out[5]=

These are the deleted elements:

In[6]:=
Table[3 k + 2, {k, 0, 4}]
Out[6]=

Here there is no second list, so nothing is deleted:

In[7]:=
ResourceFunction["UnsortedComplement"][Range[15], SameTest -> (Mod[#1, 3] === Mod[#2, 3] &)]
Out[7]=

Properties and Relations (2) 

Complement deletes elements, reduces remaining elements to one occurrence of each, and sorts:

In[8]:=
Complement[{4, 4, 4, 4, 3, 3, 3, 2, 2, 1}, {3, 2}]
Out[8]=

UnsortedComplement only deletes elements:

In[9]:=
ResourceFunction[
 "UnsortedComplement"][{4, 4, 4, 4, 3, 3, 3, 2, 2, 1}, {3, 2}]
Out[9]=

Make two lists:

In[10]:=
a = RandomInteger[{0, 9}, {10}]
Out[10]=
In[11]:=
b = RandomInteger[{0, 9}, {10}]
Out[11]=

Union deletes duplicates and sorts:

In[12]:=
ResourceFunction["UnsortedComplement"][a, b]
Out[12]=
In[13]:=
Union[ResourceFunction["UnsortedComplement"][a, b]]
Out[13]=
In[14]:=
Complement[a, b]
Out[14]=

Publisher

George Beck

Requirements

Wolfram Language 11.3 (March 2018) or above

Version History

  • 1.0.0 – 12 February 2019

Related Resources

License Information