blob: dd85ec76357a7e9b54d357357f4d3001950e68bc [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
Raymond Hettingere4905022005-04-10 17:32:35 +000033The set classes are implemented using dictionaries. Accordingly, the
34requirements for set elements are the same as those for dictionary keys;
35namely, that the element defines both \method{__eq__} and \method{__hash__}.
36As a result, sets
Fred Draked10c6c92002-08-23 17:22:36 +000037cannot contain mutable elements such as lists or dictionaries.
38However, they can contain immutable collections such as tuples or
Raymond Hettingerfa8dd5f2002-08-23 18:10:54 +000039instances of \class{ImmutableSet}. For convenience in implementing
Fred Draked10c6c92002-08-23 17:22:36 +000040sets of sets, inner sets are automatically converted to immutable
41form, for example, \code{Set([Set(['dog'])])} is transformed to
Raymond Hettinger584cb192002-08-23 15:18:38 +000042\code{Set([ImmutableSet(['dog'])])}.
43
44\begin{classdesc}{Set}{\optional{iterable}}
45Constructs a new empty \class{Set} object. If the optional \var{iterable}
46parameter is supplied, updates the set with elements obtained from iteration.
47All of the elements in \var{iterable} should be immutable or be transformable
Fred Draked10c6c92002-08-23 17:22:36 +000048to an immutable using the protocol described in
49section~\ref{immutable-transforms}.
Raymond Hettinger584cb192002-08-23 15:18:38 +000050\end{classdesc}
51
52\begin{classdesc}{ImmutableSet}{\optional{iterable}}
53Constructs a new empty \class{ImmutableSet} object. If the optional
54\var{iterable} parameter is supplied, updates the set with elements obtained
55from iteration. All of the elements in \var{iterable} should be immutable or
Fred Draked10c6c92002-08-23 17:22:36 +000056be transformable to an immutable using the protocol described in
57section~\ref{immutable-transforms}.
Raymond Hettinger584cb192002-08-23 15:18:38 +000058
59Because \class{ImmutableSet} objects provide a \method{__hash__()} method,
60they can be used as set elements or as dictionary keys. \class{ImmutableSet}
61objects do not have methods for adding or removing elements, so all of the
62elements must be known when the constructor is called.
63\end{classdesc}
64
65
Fred Drake2e3ae212003-01-06 15:50:32 +000066\subsection{Set Objects \label{set-objects}}
Raymond Hettinger584cb192002-08-23 15:18:38 +000067
68Instances of \class{Set} and \class{ImmutableSet} both provide
69the following operations:
70
Raymond Hettinger7ceb29e2003-08-16 00:56:40 +000071\begin{tableiii}{c|c|l}{code}{Operation}{Equivalent}{Result}
72 \lineiii{len(\var{s})}{}{cardinality of set \var{s}}
Raymond Hettinger584cb192002-08-23 15:18:38 +000073
74 \hline
Raymond Hettinger7ceb29e2003-08-16 00:56:40 +000075 \lineiii{\var{x} in \var{s}}{}
Fred Draked10c6c92002-08-23 17:22:36 +000076 {test \var{x} for membership in \var{s}}
Raymond Hettinger7ceb29e2003-08-16 00:56:40 +000077 \lineiii{\var{x} not in \var{s}}{}
Fred Draked10c6c92002-08-23 17:22:36 +000078 {test \var{x} for non-membership in \var{s}}
Raymond Hettinger7ceb29e2003-08-16 00:56:40 +000079 \lineiii{\var{s}.issubset(\var{t})}{\code{\var{s} <= \var{t}}}
80 {test whether every element in \var{s} is in \var{t}}
81 \lineiii{\var{s}.issuperset(\var{t})}{\code{\var{s} >= \var{t}}}
82 {test whether every element in \var{t} is in \var{s}}
Raymond Hettinger584cb192002-08-23 15:18:38 +000083
84 \hline
Fred Drake447083e2005-01-19 07:24:34 +000085 \lineiii{\var{s}.union(\var{t})}{\var{s} \textbar{} \var{t}}
Fred Draked10c6c92002-08-23 17:22:36 +000086 {new set with elements from both \var{s} and \var{t}}
Raymond Hettinger7ceb29e2003-08-16 00:56:40 +000087 \lineiii{\var{s}.intersection(\var{t})}{\var{s} \&\ \var{t}}
Fred Draked10c6c92002-08-23 17:22:36 +000088 {new set with elements common to \var{s} and \var{t}}
Raymond Hettinger7ceb29e2003-08-16 00:56:40 +000089 \lineiii{\var{s}.difference(\var{t})}{\var{s} - \var{t}}
Fred Draked10c6c92002-08-23 17:22:36 +000090 {new set with elements in \var{s} but not in \var{t}}
Raymond Hettinger7ceb29e2003-08-16 00:56:40 +000091 \lineiii{\var{s}.symmetric_difference(\var{t})}{\var{s} \^\ \var{t}}
Fred Draked10c6c92002-08-23 17:22:36 +000092 {new set with elements in either \var{s} or \var{t} but not both}
Raymond Hettinger7ceb29e2003-08-16 00:56:40 +000093 \lineiii{\var{s}.copy()}{}
Fred Draked10c6c92002-08-23 17:22:36 +000094 {new set with a shallow copy of \var{s}}
Raymond Hettinger7ceb29e2003-08-16 00:56:40 +000095\end{tableiii}
Raymond Hettinger584cb192002-08-23 15:18:38 +000096
Raymond Hettingerd4462302003-11-26 17:52:45 +000097Note, the non-operator versions of \method{union()},
Raymond Hettinger6a180122003-08-17 08:34:09 +000098\method{intersection()}, \method{difference()}, and
99\method{symmetric_difference()} will accept any iterable as an argument.
100In contrast, their operator based counterparts require their arguments to
101be sets. This precludes error-prone constructions like
102\code{Set('abc') \&\ 'cbs'} in favor of the more readable
103\code{Set('abc').intersection('cbs')}.
104\versionchanged[Formerly all arguments were required to be sets]{2.3.1}
105
Tim Petersea76c982002-08-25 18:43:10 +0000106In addition, both \class{Set} and \class{ImmutableSet}
107support set to set comparisons. Two sets are equal if and only if
108every element of each set is contained in the other (each is a subset
109of the other).
110A set is less than another set if and only if the first set is a proper
111subset of the second set (is a subset, but is not equal).
112A set is greater than another set if and only if the first set is a proper
113superset of the second set (is a superset, but is not equal).
Raymond Hettinger584cb192002-08-23 15:18:38 +0000114
Raymond Hettinger3801ec72003-01-15 15:46:05 +0000115The subset and equality comparisons do not generalize to a complete
116ordering function. For example, any two disjoint sets are not equal and
Raymond Hettinger7ceb29e2003-08-16 00:56:40 +0000117are not subsets of each other, so \emph{all} of the following return
118\code{False}: \code{\var{a}<\var{b}}, \code{\var{a}==\var{b}}, or
119\code{\var{a}>\var{b}}.
Raymond Hettinger3801ec72003-01-15 15:46:05 +0000120Accordingly, sets do not implement the \method{__cmp__} method.
121
122Since sets only define partial ordering (subset relationships), the output
123of the \method{list.sort()} method is undefined for lists of sets.
124
Raymond Hettinger584cb192002-08-23 15:18:38 +0000125The following table lists operations available in \class{ImmutableSet}
126but not found in \class{Set}:
127
Raymond Hettinger7ceb29e2003-08-16 00:56:40 +0000128\begin{tableii}{c|l}{code}{Operation}{Result}
Fred Draked10c6c92002-08-23 17:22:36 +0000129 \lineii{hash(\var{s})}{returns a hash value for \var{s}}
130\end{tableii}
Raymond Hettinger584cb192002-08-23 15:18:38 +0000131
132The following table lists operations available in \class{Set}
133but not found in \class{ImmutableSet}:
134
Raymond Hettinger7ceb29e2003-08-16 00:56:40 +0000135\begin{tableiii}{c|c|l}{code}{Operation}{Equivalent}{Result}
Raymond Hettinger16ffbc32005-07-01 23:00:13 +0000136 \lineiii{\var{s}.update(\var{t})}
Fred Drake447083e2005-01-19 07:24:34 +0000137 {\var{s} \textbar= \var{t}}
Fred Draked10c6c92002-08-23 17:22:36 +0000138 {return set \var{s} with elements added from \var{t}}
Raymond Hettinger7ceb29e2003-08-16 00:56:40 +0000139 \lineiii{\var{s}.intersection_update(\var{t})}
140 {\var{s} \&= \var{t}}
Fred Draked10c6c92002-08-23 17:22:36 +0000141 {return set \var{s} keeping only elements also found in \var{t}}
Raymond Hettinger7ceb29e2003-08-16 00:56:40 +0000142 \lineiii{\var{s}.difference_update(\var{t})}
143 {\var{s} -= \var{t}}
Fred Draked10c6c92002-08-23 17:22:36 +0000144 {return set \var{s} after removing elements found in \var{t}}
Raymond Hettinger7ceb29e2003-08-16 00:56:40 +0000145 \lineiii{\var{s}.symmetric_difference_update(\var{t})}
146 {\var{s} \textasciicircum= \var{t}}
Fred Draked10c6c92002-08-23 17:22:36 +0000147 {return set \var{s} with elements from \var{s} or \var{t}
148 but not both}
Raymond Hettinger584cb192002-08-23 15:18:38 +0000149
150 \hline
Raymond Hettinger7ceb29e2003-08-16 00:56:40 +0000151 \lineiii{\var{s}.add(\var{x})}{}
Fred Drake2e3ae212003-01-06 15:50:32 +0000152 {add element \var{x} to set \var{s}}
Raymond Hettinger7ceb29e2003-08-16 00:56:40 +0000153 \lineiii{\var{s}.remove(\var{x})}{}
154 {remove \var{x} from set \var{s}; raises KeyError if not present}
155 \lineiii{\var{s}.discard(\var{x})}{}
Fred Drake2e3ae212003-01-06 15:50:32 +0000156 {removes \var{x} from set \var{s} if present}
Raymond Hettinger7ceb29e2003-08-16 00:56:40 +0000157 \lineiii{\var{s}.pop()}{}
158 {remove and return an arbitrary element from \var{s}; raises
159 KeyError if empty}
Raymond Hettinger7ceb29e2003-08-16 00:56:40 +0000160 \lineiii{\var{s}.clear()}{}
Fred Drake2e3ae212003-01-06 15:50:32 +0000161 {remove all elements from set \var{s}}
Raymond Hettinger7ceb29e2003-08-16 00:56:40 +0000162\end{tableiii}
Raymond Hettinger584cb192002-08-23 15:18:38 +0000163
Raymond Hettinger16ffbc32005-07-01 23:00:13 +0000164Note, the non-operator versions of \method{update()},
Raymond Hettinger6a180122003-08-17 08:34:09 +0000165\method{intersection_update()}, \method{difference_update()}, and
166\method{symmetric_difference_update()} will accept any iterable as
167an argument.
168\versionchanged[Formerly all arguments were required to be sets]{2.3.1}
169
Raymond Hettinger16ffbc32005-07-01 23:00:13 +0000170Also note, the module also includes a \method{union_update()} method
171which is an alias for \method{update()}. The method is included for
Georg Brandl08c02db2005-07-22 18:39:19 +0000172backwards compatibility. Programmers should prefer the
Neal Norwitz26f4c232005-11-03 04:39:09 +0000173\method{update()} method because it is supported by the builtin
Raymond Hettinger16ffbc32005-07-01 23:00:13 +0000174\class{set()} and \class{frozenset()} types.
Raymond Hettinger584cb192002-08-23 15:18:38 +0000175
Fred Drake2e3ae212003-01-06 15:50:32 +0000176\subsection{Example \label{set-example}}
Raymond Hettinger584cb192002-08-23 15:18:38 +0000177
178\begin{verbatim}
179>>> from sets import Set
180>>> engineers = Set(['John', 'Jane', 'Jack', 'Janice'])
181>>> programmers = Set(['Jack', 'Sam', 'Susan', 'Janice'])
Raymond Hettinger7ceb29e2003-08-16 00:56:40 +0000182>>> managers = Set(['Jane', 'Jack', 'Susan', 'Zack'])
183>>> employees = engineers | programmers | managers # union
184>>> engineering_management = engineers & managers # intersection
185>>> fulltime_management = managers - engineers - programmers # difference
186>>> engineers.add('Marvin') # add element
Raymond Hettinger584cb192002-08-23 15:18:38 +0000187>>> print engineers
188Set(['Jane', 'Marvin', 'Janice', 'John', 'Jack'])
189>>> employees.issuperset(engineers) # superset test
190False
Raymond Hettinger6a180122003-08-17 08:34:09 +0000191>>> employees.union_update(engineers) # update from another set
Raymond Hettinger584cb192002-08-23 15:18:38 +0000192>>> employees.issuperset(engineers)
193True
Raymond Hettingerd4568492003-11-16 13:44:19 +0000194>>> for group in [engineers, programmers, managers, employees]:
Raymond Hettinger3801ec72003-01-15 15:46:05 +0000195... group.discard('Susan') # unconditionally remove element
196... print group
197...
Raymond Hettinger584cb192002-08-23 15:18:38 +0000198Set(['Jane', 'Marvin', 'Janice', 'John', 'Jack'])
199Set(['Janice', 'Jack', 'Sam'])
200Set(['Jane', 'Zack', 'Jack'])
201Set(['Jack', 'Sam', 'Jane', 'Marvin', 'Janice', 'John', 'Zack'])
202\end{verbatim}
203
204
205\subsection{Protocol for automatic conversion to immutable
206 \label{immutable-transforms}}
207
208Sets can only contain immutable elements. For convenience, mutable
209\class{Set} objects are automatically copied to an \class{ImmutableSet}
210before being added as a set element.
211
Fred Draked10c6c92002-08-23 17:22:36 +0000212The mechanism is to always add a hashable element, or if it is not
213hashable, the element is checked to see if it has an
Raymond Hettinger2835e372003-02-14 03:42:11 +0000214\method{__as_immutable__()} method which returns an immutable equivalent.
Raymond Hettinger584cb192002-08-23 15:18:38 +0000215
Raymond Hettinger2835e372003-02-14 03:42:11 +0000216Since \class{Set} objects have a \method{__as_immutable__()} method
Raymond Hettinger584cb192002-08-23 15:18:38 +0000217returning an instance of \class{ImmutableSet}, it is possible to
218construct sets of sets.
219
220A similar mechanism is needed by the \method{__contains__()} and
221\method{remove()} methods which need to hash an element to check
222for membership in a set. Those methods check an element for hashability
Raymond Hettinger2835e372003-02-14 03:42:11 +0000223and, if not, check for a \method{__as_temporarily_immutable__()} method
Raymond Hettinger584cb192002-08-23 15:18:38 +0000224which returns the element wrapped by a class that provides temporary
225methods for \method{__hash__()}, \method{__eq__()}, and \method{__ne__()}.
226
227The alternate mechanism spares the need to build a separate copy of
228the original mutable object.
229
Raymond Hettinger2835e372003-02-14 03:42:11 +0000230\class{Set} objects implement the \method{__as_temporarily_immutable__()}
Fred Draked10c6c92002-08-23 17:22:36 +0000231method which returns the \class{Set} object wrapped by a new class
Raymond Hettinger584cb192002-08-23 15:18:38 +0000232\class{_TemporarilyImmutableSet}.
233
234The two mechanisms for adding hashability are normally invisible to the
235user; however, a conflict can arise in a multi-threaded environment
Raymond Hettingerfa8dd5f2002-08-23 18:10:54 +0000236where one thread is updating a set while another has temporarily wrapped it
Raymond Hettinger584cb192002-08-23 15:18:38 +0000237in \class{_TemporarilyImmutableSet}. In other words, sets of mutable sets
238are not thread-safe.
Raymond Hettinger16ffbc32005-07-01 23:00:13 +0000239
240
241\subsection{Comparison to the built-in \class{set} types
242 \label{comparison-to-builtin-set}}
243
244The built-in \class{set} and \class{frozenset} types were designed based
245on lessons learned from the \module{sets} module. The key differences are:
246
247\begin{itemize}
248\item \class{Set} and \class{ImmutableSet} were renamed to \class{set} and
249 \class{frozenset}.
250\item There is no equivalent to \class{BaseSet}. Instead, use
251 \code{isinstance(x, (set, frozenset))}.
252\item The hash algorithm for the built-ins performs significantly better
253 (fewer collisions) for most datasets.
254\item The built-in versions have more space efficient pickles.
255\item The built-in versions do not have a \method{union_update()} method.
256 Instead, use the \method{update()} method which is equivalent.
Georg Brandl08c02db2005-07-22 18:39:19 +0000257\item The built-in versions do not have a \method{_repr(sorted=True)} method.
Raymond Hettinger16ffbc32005-07-01 23:00:13 +0000258 Instead, use the built-in \function{repr()} and \function{sorted()}
259 functions: \code{repr(sorted(s))}.
260\item The built-in version does not have a protocol for automatic conversion
261 to immutable. Many found this feature to be confusing and no one
262 in the community reported having found real uses for it.
263\end{itemize}