blob: 6d49b16e9d13a8c4ba4185eac419e527193f5ef7 [file] [log] [blame]
Raymond Hettinger584cb192002-08-23 15:18:38 +00001\section{\module{sets} ---
2 Unordered collections of unique elements}
3
4\declaremodule{standard}{sets}
5\modulesynopsis{Implementation of sets of unique elements.}
6\moduleauthor{Greg V. Wilson}{gvwilson@nevex.com}
7\moduleauthor{Alex Martelli}{aleax@aleax.it}
8\moduleauthor{Guido van Rossum}{guido@python.org}
9\sectionauthor{Raymond D. Hettinger}{python@rcn.com}
10
11\versionadded{2.3}
12
13The \module{sets} module provides classes for constructing and manipulating
14unordered collections of unique elements. Common uses include membership
15testing, removing duplicates from a sequence, and computing standard math
16operations on sets such as intersection, union, difference, and symmetric
17difference.
18
Fred Draked10c6c92002-08-23 17:22:36 +000019Like other collections, sets support \code{\var{x} in \var{set}},
20\code{len(\var{set})}, and \code{for \var{x} in \var{set}}. Being an
21unordered collection, sets do not record element position or order of
22insertion. Accordingly, sets do not support indexing, slicing, or
23other sequence-like behavior.
Raymond Hettinger584cb192002-08-23 15:18:38 +000024
25Most set applications use the \class{Set} class which provides every set
26method except for \method{__hash__()}. For advanced applications requiring
27a hash method, the \class{ImmutableSet} class adds a \method{__hash__()}
28method but omits methods which alter the contents of the set. Both
29\class{Set} and \class{ImmutableSet} derive from \class{BaseSet}, an
30abstract class useful for determining whether something is a set:
Fred Draked10c6c92002-08-23 17:22:36 +000031\code{isinstance(\var{obj}, BaseSet)}.
Raymond Hettinger584cb192002-08-23 15:18:38 +000032
Fred Draked10c6c92002-08-23 17:22:36 +000033The set classes are implemented using dictionaries. As a result, sets
34cannot contain mutable elements such as lists or dictionaries.
35However, they can contain immutable collections such as tuples or
Raymond Hettingerfa8dd5f2002-08-23 18:10:54 +000036instances of \class{ImmutableSet}. For convenience in implementing
Fred Draked10c6c92002-08-23 17:22:36 +000037sets of sets, inner sets are automatically converted to immutable
38form, for example, \code{Set([Set(['dog'])])} is transformed to
Raymond Hettinger584cb192002-08-23 15:18:38 +000039\code{Set([ImmutableSet(['dog'])])}.
40
41\begin{classdesc}{Set}{\optional{iterable}}
42Constructs a new empty \class{Set} object. If the optional \var{iterable}
43parameter is supplied, updates the set with elements obtained from iteration.
44All of the elements in \var{iterable} should be immutable or be transformable
Fred Draked10c6c92002-08-23 17:22:36 +000045to an immutable using the protocol described in
46section~\ref{immutable-transforms}.
Raymond Hettinger584cb192002-08-23 15:18:38 +000047\end{classdesc}
48
49\begin{classdesc}{ImmutableSet}{\optional{iterable}}
50Constructs a new empty \class{ImmutableSet} object. If the optional
51\var{iterable} parameter is supplied, updates the set with elements obtained
52from iteration. All of the elements in \var{iterable} should be immutable or
Fred Draked10c6c92002-08-23 17:22:36 +000053be transformable to an immutable using the protocol described in
54section~\ref{immutable-transforms}.
Raymond Hettinger584cb192002-08-23 15:18:38 +000055
56Because \class{ImmutableSet} objects provide a \method{__hash__()} method,
57they can be used as set elements or as dictionary keys. \class{ImmutableSet}
58objects do not have methods for adding or removing elements, so all of the
59elements must be known when the constructor is called.
60\end{classdesc}
61
62
Fred Drake2e3ae212003-01-06 15:50:32 +000063\subsection{Set Objects \label{set-objects}}
Raymond Hettinger584cb192002-08-23 15:18:38 +000064
65Instances of \class{Set} and \class{ImmutableSet} both provide
66the following operations:
67
Raymond Hettinger7ceb29e2003-08-16 00:56:40 +000068\begin{tableiii}{c|c|l}{code}{Operation}{Equivalent}{Result}
69 \lineiii{len(\var{s})}{}{cardinality of set \var{s}}
Raymond Hettinger584cb192002-08-23 15:18:38 +000070
71 \hline
Raymond Hettinger7ceb29e2003-08-16 00:56:40 +000072 \lineiii{\var{x} in \var{s}}{}
Fred Draked10c6c92002-08-23 17:22:36 +000073 {test \var{x} for membership in \var{s}}
Raymond Hettinger7ceb29e2003-08-16 00:56:40 +000074 \lineiii{\var{x} not in \var{s}}{}
Fred Draked10c6c92002-08-23 17:22:36 +000075 {test \var{x} for non-membership in \var{s}}
Raymond Hettinger7ceb29e2003-08-16 00:56:40 +000076 \lineiii{\var{s}.issubset(\var{t})}{\code{\var{s} <= \var{t}}}
77 {test whether every element in \var{s} is in \var{t}}
78 \lineiii{\var{s}.issuperset(\var{t})}{\code{\var{s} >= \var{t}}}
79 {test whether every element in \var{t} is in \var{s}}
Raymond Hettinger584cb192002-08-23 15:18:38 +000080
81 \hline
Raymond Hettinger7ceb29e2003-08-16 00:56:40 +000082 \lineiii{\var{s}.union(\var{t})}{\var{s} | \var{t}}
Fred Draked10c6c92002-08-23 17:22:36 +000083 {new set with elements from both \var{s} and \var{t}}
Raymond Hettinger7ceb29e2003-08-16 00:56:40 +000084 \lineiii{\var{s}.intersection(\var{t})}{\var{s} \&\ \var{t}}
Fred Draked10c6c92002-08-23 17:22:36 +000085 {new set with elements common to \var{s} and \var{t}}
Raymond Hettinger7ceb29e2003-08-16 00:56:40 +000086 \lineiii{\var{s}.difference(\var{t})}{\var{s} - \var{t}}
Fred Draked10c6c92002-08-23 17:22:36 +000087 {new set with elements in \var{s} but not in \var{t}}
Raymond Hettinger7ceb29e2003-08-16 00:56:40 +000088 \lineiii{\var{s}.symmetric_difference(\var{t})}{\var{s} \^\ \var{t}}
Fred Draked10c6c92002-08-23 17:22:36 +000089 {new set with elements in either \var{s} or \var{t} but not both}
Raymond Hettinger7ceb29e2003-08-16 00:56:40 +000090 \lineiii{\var{s}.copy()}{}
Fred Draked10c6c92002-08-23 17:22:36 +000091 {new set with a shallow copy of \var{s}}
Raymond Hettinger7ceb29e2003-08-16 00:56:40 +000092\end{tableiii}
Raymond Hettinger584cb192002-08-23 15:18:38 +000093
Raymond Hettingerd4462302003-11-26 17:52:45 +000094Note, the non-operator versions of \method{union()},
Raymond Hettinger6a180122003-08-17 08:34:09 +000095\method{intersection()}, \method{difference()}, and
96\method{symmetric_difference()} will accept any iterable as an argument.
97In contrast, their operator based counterparts require their arguments to
98be sets. This precludes error-prone constructions like
99\code{Set('abc') \&\ 'cbs'} in favor of the more readable
100\code{Set('abc').intersection('cbs')}.
101\versionchanged[Formerly all arguments were required to be sets]{2.3.1}
102
Tim Petersea76c982002-08-25 18:43:10 +0000103In addition, both \class{Set} and \class{ImmutableSet}
104support set to set comparisons. Two sets are equal if and only if
105every element of each set is contained in the other (each is a subset
106of the other).
107A set is less than another set if and only if the first set is a proper
108subset of the second set (is a subset, but is not equal).
109A set is greater than another set if and only if the first set is a proper
110superset of the second set (is a superset, but is not equal).
Raymond Hettinger584cb192002-08-23 15:18:38 +0000111
Raymond Hettinger3801ec72003-01-15 15:46:05 +0000112The subset and equality comparisons do not generalize to a complete
113ordering function. For example, any two disjoint sets are not equal and
Raymond Hettinger7ceb29e2003-08-16 00:56:40 +0000114are not subsets of each other, so \emph{all} of the following return
115\code{False}: \code{\var{a}<\var{b}}, \code{\var{a}==\var{b}}, or
116\code{\var{a}>\var{b}}.
Raymond Hettinger3801ec72003-01-15 15:46:05 +0000117Accordingly, sets do not implement the \method{__cmp__} method.
118
119Since sets only define partial ordering (subset relationships), the output
120of the \method{list.sort()} method is undefined for lists of sets.
121
Raymond Hettinger584cb192002-08-23 15:18:38 +0000122The following table lists operations available in \class{ImmutableSet}
123but not found in \class{Set}:
124
Raymond Hettinger7ceb29e2003-08-16 00:56:40 +0000125\begin{tableii}{c|l}{code}{Operation}{Result}
Fred Draked10c6c92002-08-23 17:22:36 +0000126 \lineii{hash(\var{s})}{returns a hash value for \var{s}}
127\end{tableii}
Raymond Hettinger584cb192002-08-23 15:18:38 +0000128
129The following table lists operations available in \class{Set}
130but not found in \class{ImmutableSet}:
131
Raymond Hettinger7ceb29e2003-08-16 00:56:40 +0000132\begin{tableiii}{c|c|l}{code}{Operation}{Equivalent}{Result}
133 \lineiii{\var{s}.union_update(\var{t})}
134 {\var{s} |= \var{t}}
Fred Draked10c6c92002-08-23 17:22:36 +0000135 {return set \var{s} with elements added from \var{t}}
Raymond Hettinger7ceb29e2003-08-16 00:56:40 +0000136 \lineiii{\var{s}.intersection_update(\var{t})}
137 {\var{s} \&= \var{t}}
Fred Draked10c6c92002-08-23 17:22:36 +0000138 {return set \var{s} keeping only elements also found in \var{t}}
Raymond Hettinger7ceb29e2003-08-16 00:56:40 +0000139 \lineiii{\var{s}.difference_update(\var{t})}
140 {\var{s} -= \var{t}}
Fred Draked10c6c92002-08-23 17:22:36 +0000141 {return set \var{s} after removing elements found in \var{t}}
Raymond Hettinger7ceb29e2003-08-16 00:56:40 +0000142 \lineiii{\var{s}.symmetric_difference_update(\var{t})}
143 {\var{s} \textasciicircum= \var{t}}
Fred Draked10c6c92002-08-23 17:22:36 +0000144 {return set \var{s} with elements from \var{s} or \var{t}
145 but not both}
Raymond Hettinger584cb192002-08-23 15:18:38 +0000146
147 \hline
Raymond Hettinger7ceb29e2003-08-16 00:56:40 +0000148 \lineiii{\var{s}.add(\var{x})}{}
Fred Drake2e3ae212003-01-06 15:50:32 +0000149 {add element \var{x} to set \var{s}}
Raymond Hettinger7ceb29e2003-08-16 00:56:40 +0000150 \lineiii{\var{s}.remove(\var{x})}{}
151 {remove \var{x} from set \var{s}; raises KeyError if not present}
152 \lineiii{\var{s}.discard(\var{x})}{}
Fred Drake2e3ae212003-01-06 15:50:32 +0000153 {removes \var{x} from set \var{s} if present}
Raymond Hettinger7ceb29e2003-08-16 00:56:40 +0000154 \lineiii{\var{s}.pop()}{}
155 {remove and return an arbitrary element from \var{s}; raises
156 KeyError if empty}
Raymond Hettinger7ceb29e2003-08-16 00:56:40 +0000157 \lineiii{\var{s}.clear()}{}
Fred Drake2e3ae212003-01-06 15:50:32 +0000158 {remove all elements from set \var{s}}
Raymond Hettinger7ceb29e2003-08-16 00:56:40 +0000159\end{tableiii}
Raymond Hettinger584cb192002-08-23 15:18:38 +0000160
Raymond Hettingerd4462302003-11-26 17:52:45 +0000161Note, the non-operator versions of \method{union_update()},
Raymond Hettinger6a180122003-08-17 08:34:09 +0000162\method{intersection_update()}, \method{difference_update()}, and
163\method{symmetric_difference_update()} will accept any iterable as
164an argument.
165\versionchanged[Formerly all arguments were required to be sets]{2.3.1}
166
Raymond Hettinger584cb192002-08-23 15:18:38 +0000167
Fred Drake2e3ae212003-01-06 15:50:32 +0000168\subsection{Example \label{set-example}}
Raymond Hettinger584cb192002-08-23 15:18:38 +0000169
170\begin{verbatim}
171>>> from sets import Set
172>>> engineers = Set(['John', 'Jane', 'Jack', 'Janice'])
173>>> programmers = Set(['Jack', 'Sam', 'Susan', 'Janice'])
Raymond Hettinger7ceb29e2003-08-16 00:56:40 +0000174>>> managers = Set(['Jane', 'Jack', 'Susan', 'Zack'])
175>>> employees = engineers | programmers | managers # union
176>>> engineering_management = engineers & managers # intersection
177>>> fulltime_management = managers - engineers - programmers # difference
178>>> engineers.add('Marvin') # add element
Raymond Hettinger584cb192002-08-23 15:18:38 +0000179>>> print engineers
180Set(['Jane', 'Marvin', 'Janice', 'John', 'Jack'])
181>>> employees.issuperset(engineers) # superset test
182False
Raymond Hettinger6a180122003-08-17 08:34:09 +0000183>>> employees.union_update(engineers) # update from another set
Raymond Hettinger584cb192002-08-23 15:18:38 +0000184>>> employees.issuperset(engineers)
185True
Raymond Hettingerd4568492003-11-16 13:44:19 +0000186>>> for group in [engineers, programmers, managers, employees]:
Raymond Hettinger3801ec72003-01-15 15:46:05 +0000187... group.discard('Susan') # unconditionally remove element
188... print group
189...
Raymond Hettinger584cb192002-08-23 15:18:38 +0000190Set(['Jane', 'Marvin', 'Janice', 'John', 'Jack'])
191Set(['Janice', 'Jack', 'Sam'])
192Set(['Jane', 'Zack', 'Jack'])
193Set(['Jack', 'Sam', 'Jane', 'Marvin', 'Janice', 'John', 'Zack'])
194\end{verbatim}
195
196
197\subsection{Protocol for automatic conversion to immutable
198 \label{immutable-transforms}}
199
200Sets can only contain immutable elements. For convenience, mutable
201\class{Set} objects are automatically copied to an \class{ImmutableSet}
202before being added as a set element.
203
Fred Draked10c6c92002-08-23 17:22:36 +0000204The mechanism is to always add a hashable element, or if it is not
205hashable, the element is checked to see if it has an
Raymond Hettinger2835e372003-02-14 03:42:11 +0000206\method{__as_immutable__()} method which returns an immutable equivalent.
Raymond Hettinger584cb192002-08-23 15:18:38 +0000207
Raymond Hettinger2835e372003-02-14 03:42:11 +0000208Since \class{Set} objects have a \method{__as_immutable__()} method
Raymond Hettinger584cb192002-08-23 15:18:38 +0000209returning an instance of \class{ImmutableSet}, it is possible to
210construct sets of sets.
211
212A similar mechanism is needed by the \method{__contains__()} and
213\method{remove()} methods which need to hash an element to check
214for membership in a set. Those methods check an element for hashability
Raymond Hettinger2835e372003-02-14 03:42:11 +0000215and, if not, check for a \method{__as_temporarily_immutable__()} method
Raymond Hettinger584cb192002-08-23 15:18:38 +0000216which returns the element wrapped by a class that provides temporary
217methods for \method{__hash__()}, \method{__eq__()}, and \method{__ne__()}.
218
219The alternate mechanism spares the need to build a separate copy of
220the original mutable object.
221
Raymond Hettinger2835e372003-02-14 03:42:11 +0000222\class{Set} objects implement the \method{__as_temporarily_immutable__()}
Fred Draked10c6c92002-08-23 17:22:36 +0000223method which returns the \class{Set} object wrapped by a new class
Raymond Hettinger584cb192002-08-23 15:18:38 +0000224\class{_TemporarilyImmutableSet}.
225
226The two mechanisms for adding hashability are normally invisible to the
227user; however, a conflict can arise in a multi-threaded environment
Raymond Hettingerfa8dd5f2002-08-23 18:10:54 +0000228where one thread is updating a set while another has temporarily wrapped it
Raymond Hettinger584cb192002-08-23 15:18:38 +0000229in \class{_TemporarilyImmutableSet}. In other words, sets of mutable sets
230are not thread-safe.