Skip to content

Union

Status: Stable

documented, exercised by the test suite and/or worked examples, with no known limitations recorded.

Description

Union[list]
    gives the sorted list of distinct elements in list.
Union[l1, l2, ...]
    gives the sorted list of distinct elements appearing in any of the
    input lists (set union).
Comparison is by canonical structural equality.

Examples

All examples below are verified against the current Mathilda build.

In[1]:= Union[{1, 2, 1, 3, 6, 2, 2}]
Out[1]= {1, 2, 3, 6}

In[2]:= Union[{a, b, a, c}, {d, a, e, b}, {c, a}]
Out[2]= {a, b, c, d, e}

Implementation notes

Algorithm. builtin_union concatenates the elements of all argument lists (which must share a common head), sorts the combined Expr** array with qsort under the canonical expr_compare order, then removes adjacent duplicates — expr_eq by default, or an optional SameTest -> f which is evaluated per adjacent pair. The result is the sorted, deduplicated list. (DeleteDuplicates in the same file does the order-preserving variant using a hash table keyed on expr_hash/expr_eq.)

  • Flat, OneIdentity, Protected, ReadProtected.
  • All expressions must have the same head.
  • Result has the same head as the inputs.

Attributes: Flat, OneIdentity, Protected, ReadProtected.

Implementation status

Stable — documented, exercised by the test suite and/or worked examples, with no known limitations recorded.

References

Notes & additional examples

Worked examples

In[1]:= Union[{3, 1, 2, 1, 3}]
Out[1]= {1, 2, 3}

With several arguments Union performs a true set union, merging and deduplicating across all lists:

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

Deduplication uses canonical structural equality, so symbolic and compound elements are handled too, and the result is returned in canonical sorted order:

In[1]:= Union[{x, Sin[y], x, 1, Sin[y]}]
Out[1]= {1, x, Sin[y]}

Notes

Union[list] gives the sorted list of distinct elements; Union[l1, l2, ...] gives the set union. Comparison is by canonical structural equality, and the output is always sorted with duplicates removed.