The new sets module contains an implementation of a set datatype. The Set class is for mutable sets, sets that can have members added and removed. The ImmutableSet class is for sets that can't be modified, and instances of ImmutableSet can therefore be used as dictionary keys. Sets are built on top of dictionaries, so the elements within a set must be hashable.
Here's a simple example:
>>> import sets >>> S = sets.Set([1,2,3]) >>> S Set([1, 2, 3]) >>> 1 in S True >>> 0 in S False >>> S.add(5) >>> S.remove(3) >>> S Set([1, 2, 5]) >>>
The union and intersection of sets can be computed with the
union() and intersection() methods; an alternative
notation uses the bitwise operators &
and |
.
Mutable sets also have in-place versions of these methods,
union_update() and intersection_update().
>>> S1 = sets.Set([1,2,3]) >>> S2 = sets.Set([4,5,6]) >>> S1.union(S2) Set([1, 2, 3, 4, 5, 6]) >>> S1 | S2 # Alternative notation Set([1, 2, 3, 4, 5, 6]) >>> S1.intersection(S2) Set([]) >>> S1 & S2 # Alternative notation Set([]) >>> S1.union_update(S2) >>> S1 Set([1, 2, 3, 4, 5, 6]) >>>
It's also possible to take the symmetric difference of two sets. This
is the set of all elements in the union that aren't in the
intersection. Another way of putting it is that the symmetric
difference contains all elements that are in exactly one
set. Again, there's an alternative notation (^
), and an
in-place version with the ungainly name
symmetric_difference_update().
>>> S1 = sets.Set([1,2,3,4]) >>> S2 = sets.Set([3,4,5,6]) >>> S1.symmetric_difference(S2) Set([1, 2, 5, 6]) >>> S1 ^ S2 Set([1, 2, 5, 6]) >>>
There are also issubset() and issuperset() methods for checking whether one set is a subset or superset of another:
>>> S1 = sets.Set([1,2,3]) >>> S2 = sets.Set([2,3]) >>> S2.issubset(S1) True >>> S1.issubset(S2) False >>> S1.issuperset(S2) True >>>
See Also:
See About this document... for information on suggesting changes.