Wolfram Research

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 list any 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

Delete specified elements from a list:

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

Scope

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]=

Options

Use equivalence classes based on absolute value:

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

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

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

These are the deleted elements:

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

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

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

Properties and Relations

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

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

UnsortedComplement only deletes elements:

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

Make two lists:

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

Union deletes duplicates and sorts:

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

Requirements

Wolfram Language 11.3 (March 2018) or above

Resource History

See Also

License Information