|
25 | 25 | If you want to understand the complete implementation and design |
26 | 26 | rationale, refer to the PEP for a particular new feature. |
27 | 27 |
|
| 28 | +%====================================================================== |
| 29 | +\section{PEP 218: Built-In Set Objects} |
| 30 | + |
| 31 | +Two new built-in types, \function{set(iterable)} and |
| 32 | +\function{frozenset(iterable)} provide high speed data types for |
| 33 | +membership testing, for eliminating duplicates from sequences, and |
| 34 | +for mathematical operations like unions, intersections, differences, |
| 35 | +and symmetric differences. |
| 36 | + |
| 37 | +\begin{verbatim} |
| 38 | +>>> a = set('abracadabra') # form a set from a string |
| 39 | +>>> 'z' in a # fast membership testing |
| 40 | +False |
| 41 | +>>> a # unique letters in a |
| 42 | +set(['a', 'r', 'b', 'c', 'd']) |
| 43 | +>>> ''.join(a) # convert back into a string |
| 44 | +'arbcd' |
| 45 | +>>> b = set('alacazam') # form a second set |
| 46 | +>>> a - b # letters in a but not in b |
| 47 | +set(['r', 'd', 'b']) |
| 48 | +>>> a | b # letters in either a or b |
| 49 | +set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l']) |
| 50 | +>>> a & b # letters in both a and b |
| 51 | +set(['a', 'c']) |
| 52 | +>>> a ^ b # letters in a or b but not both |
| 53 | +set(['r', 'd', 'b', 'm', 'z', 'l']) |
| 54 | +>>> a.add('z') # add a new element |
| 55 | +>>> a.update('wxy') # add multiple new elements |
| 56 | +>>> a |
| 57 | +set(['a', 'c', 'b', 'd', 'r', 'w', 'y', 'x', 'z']) |
| 58 | +>>> a.remove('x') # take one element out |
| 59 | +>>> a |
| 60 | +set(['a', 'c', 'b', 'd', 'r', 'w', 'y', 'z']) |
| 61 | +\end{verbatim} |
| 62 | + |
| 63 | +The type \function{frozenset()} is an immutable version of \function{set()}. |
| 64 | +Since it is immutable and hashable, it may be used as a dictionary key or |
| 65 | +as a member of another set. Accordingly, it does not have methods |
| 66 | +like \method{add()} and \method{remove()} which could alter its contents. |
| 67 | + |
| 68 | +\begin{seealso} |
| 69 | +\seepep{218}{Adding a Built-In Set Object Type}{Originally proposed by |
| 70 | +Greg Wilson and ultimately implemented by Raymond Hettinger.} |
| 71 | +\end{seealso} |
28 | 72 |
|
29 | 73 | %====================================================================== |
30 | 74 | \section{PEP 322: Reverse Iteration} |
|
0 commit comments