61
Changed in version 2.3.1: Formerly all arguments were required to be sets.
Also note, the module also includes a
union_update()
method which is an alias for
update()
. The method is included for backwards compatibility. Programmers should
prefer the
update()
method because it is supported by the built-in
set()
and
frozenset()
types.
8.7.2. Example
>>> from sets import Set
>>> engineers = Set(['John', 'Jane', 'Jack', 'Janice'])
>>> programmers = Set(['Jack', 'Sam', 'Susan', 'Janice'])
>>> managers = Set(['Jane', 'Jack', 'Susan', 'Zack'])
>>> employees = engineers | programmers | managers # union
>>> engineering_management = engineers & managers # intersection
>>> fulltime_management = managers - engineers - programmers # difference
>>> engineers.add('Marvin') # add element
>>> print engineers
Set(['Jane', 'Marvin', 'Janice', 'John', 'Jack'])
>>> employees.issuperset(engineers) # superset test
False
>>> employees.update(engineers) # update from another set
>>> employees.issuperset(engineers)
True
>>> for group in [engineers, programmers, managers, employees]:
... group.discard('Susan') # unconditionally remove element
... print group
...
Set(['Jane', 'Marvin', 'Janice', 'John', 'Jack'])
Set(['Janice', 'Jack', 'Sam'])
Set(['Jane', 'Zack', 'Jack'])
Set(['Jack', 'Sam', 'Jane', 'Marvin', 'Janice', 'John', 'Zack'])
8.7.3. Protocol for automatic conversion to immutable
Sets can only contain immutable elements. For convenience, mutable
Set
objects are
automatically copied to an
ImmutableSet
before being added as a set element.
The mechanism is to always add a hashable element, or if it is not hashable, the element
is checked to see if it has an
__as_immutable__()
method which returns an immutable
equivalent.
Since
Set
objects have a
__as_immutable__()
method returning an instance of
ImmutableSet
, it is possible to construct sets of sets.
A similar mechanism is needed by the
__contains__()
and
remove()
methods which