New in version 2.3.
The sets module provides classes for constructing and manipulating unordered collections of unique elements. Common uses include membership testing, removing duplicates from a sequence, and computing standard math operations on sets such as intersection, union, difference, and symmetric difference.
Like other collections, sets support
x in set,
for x in set. Being an
unordered collection, sets do not record element position or order of
insertion. Accordingly, sets do not support indexing, slicing, or
other sequence-like behavior.
Most set applications use the Set class which provides every set
method except for __hash__(). For advanced applications requiring
a hash method, the ImmutableSet class adds a __hash__()
method but omits methods which alter the contents of the set. Both
Set and ImmutableSet derive from BaseSet, an
abstract class useful for determining whether something is a set:
The set classes are implemented using dictionaries. As a result, sets
cannot contain mutable elements such as lists or dictionaries.
However, they can contain immutable collections such as tuples or
instances of ImmutableSet. For convenience in implementing
sets of sets, inner sets are automatically converted to immutable
form, for example,
Set([Set(['dog'])]) is transformed to
Because ImmutableSet objects provide a __hash__() method, they can be used as set elements or as dictionary keys. ImmutableSet objects do not have methods for adding or removing elements, so all of the elements must be known when the constructor is called.