A set is a collection in which no element is repeated, which may be able to enumerate its elements according to an ordering criterion (an "ordered set") or retain no order (an "unordered set").
A set is a collection in which no element is repeated. It is often implemented by hashing the objects as they are added to the set, and comparing against those hashes for operations on the set.
In the C++ standard library in particular, the std::set
is able to enumerate its elements according to a specific strict weak ordering criterion set on container construction. To achieve this, it is typically implemented by a binary tree. By contrast, the std::unordered_set
stores unique elements in no particular order, and allows for fast retrieval of individual elements based on their value.
In Python, there are currently two built-in set types, set and frozenset. set
is mutable, i.e. the contents can be changed and it has no hash value and cannot be used as either a dictionary key or as an element of another set. The frozenset
type is immutable and hashable.
Common operations on sets:
- add
- remove
- find (check membership)
- union, intersection, difference