Raymond Hettinger | e52f3b1 | 2004-01-29 07:27:45 +0000 | [diff] [blame] | 1 | \section{\module{collections} --- |
Raymond Hettinger | 5c5eb86 | 2004-02-07 21:13:00 +0000 | [diff] [blame] | 2 | High-performance container datatypes} |
Raymond Hettinger | e52f3b1 | 2004-01-29 07:27:45 +0000 | [diff] [blame] | 3 | |
| 4 | \declaremodule{standard}{collections} |
| 5 | \modulesynopsis{High-performance datatypes} |
| 6 | \moduleauthor{Raymond Hettinger}{python@rcn.com} |
| 7 | \sectionauthor{Raymond Hettinger}{python@rcn.com} |
| 8 | \versionadded{2.4} |
| 9 | |
| 10 | |
Guido van Rossum | 1968ad3 | 2006-02-25 22:38:04 +0000 | [diff] [blame] | 11 | This module implements high-performance container datatypes. Currently, |
| 12 | there are two datatypes, deque and defaultdict. |
| 13 | Future additions may include B-trees and Fibonacci heaps. |
| 14 | \versionchanged[Added defaultdict]{2.5} |
Raymond Hettinger | e52f3b1 | 2004-01-29 07:27:45 +0000 | [diff] [blame] | 15 | |
| 16 | \begin{funcdesc}{deque}{\optional{iterable}} |
| 17 | Returns a new deque objected initialized left-to-right (using |
| 18 | \method{append()}) with data from \var{iterable}. If \var{iterable} |
| 19 | is not specified, the new deque is empty. |
| 20 | |
Raymond Hettinger | 5c5eb86 | 2004-02-07 21:13:00 +0000 | [diff] [blame] | 21 | Deques are a generalization of stacks and queues (the name is pronounced |
| 22 | ``deck'' and is short for ``double-ended queue''). Deques support |
| 23 | thread-safe, memory efficient appends and pops from either side of the deque |
| 24 | with approximately the same \code{O(1)} performance in either direction. |
| 25 | |
| 26 | Though \class{list} objects support similar operations, they are optimized |
| 27 | for fast fixed-length operations and incur \code{O(n)} memory movement costs |
| 28 | for \samp{pop(0)} and \samp{insert(0, v)} operations which change both the |
| 29 | size and position of the underlying data representation. |
Raymond Hettinger | e52f3b1 | 2004-01-29 07:27:45 +0000 | [diff] [blame] | 30 | \versionadded{2.4} |
| 31 | \end{funcdesc} |
| 32 | |
| 33 | Deque objects support the following methods: |
| 34 | |
| 35 | \begin{methoddesc}{append}{x} |
| 36 | Add \var{x} to the right side of the deque. |
| 37 | \end{methoddesc} |
| 38 | |
| 39 | \begin{methoddesc}{appendleft}{x} |
| 40 | Add \var{x} to the left side of the deque. |
| 41 | \end{methoddesc} |
| 42 | |
| 43 | \begin{methoddesc}{clear}{} |
| 44 | Remove all elements from the deque leaving it with length 0. |
| 45 | \end{methoddesc} |
| 46 | |
Raymond Hettinger | 3ba85c2 | 2004-02-06 19:04:56 +0000 | [diff] [blame] | 47 | \begin{methoddesc}{extend}{iterable} |
| 48 | Extend the right side of the deque by appending elements from |
| 49 | the iterable argument. |
| 50 | \end{methoddesc} |
| 51 | |
| 52 | \begin{methoddesc}{extendleft}{iterable} |
| 53 | Extend the left side of the deque by appending elements from |
| 54 | \var{iterable}. Note, the series of left appends results in |
| 55 | reversing the order of elements in the iterable argument. |
| 56 | \end{methoddesc} |
| 57 | |
Raymond Hettinger | e52f3b1 | 2004-01-29 07:27:45 +0000 | [diff] [blame] | 58 | \begin{methoddesc}{pop}{} |
| 59 | Remove and return an element from the right side of the deque. |
Raymond Hettinger | 738ec90 | 2004-02-29 02:15:56 +0000 | [diff] [blame] | 60 | If no elements are present, raises a \exception{IndexError}. |
Raymond Hettinger | e52f3b1 | 2004-01-29 07:27:45 +0000 | [diff] [blame] | 61 | \end{methoddesc} |
| 62 | |
| 63 | \begin{methoddesc}{popleft}{} |
| 64 | Remove and return an element from the left side of the deque. |
Raymond Hettinger | 738ec90 | 2004-02-29 02:15:56 +0000 | [diff] [blame] | 65 | If no elements are present, raises a \exception{IndexError}. |
| 66 | \end{methoddesc} |
| 67 | |
Raymond Hettinger | 4aec61e | 2005-03-18 21:20:23 +0000 | [diff] [blame] | 68 | \begin{methoddesc}{remove}{value} |
| 69 | Removed the first occurrence of \var{value}. If not found, |
| 70 | raises a \exception{ValueError}. |
| 71 | \versionadded{2.5} |
| 72 | \end{methoddesc} |
| 73 | |
Raymond Hettinger | 5c5eb86 | 2004-02-07 21:13:00 +0000 | [diff] [blame] | 74 | \begin{methoddesc}{rotate}{n} |
| 75 | Rotate the deque \var{n} steps to the right. If \var{n} is |
| 76 | negative, rotate to the left. Rotating one step to the right |
Raymond Hettinger | f5f9a370 | 2004-04-30 22:52:50 +0000 | [diff] [blame] | 77 | is equivalent to: \samp{d.appendleft(d.pop())}. |
Raymond Hettinger | 5c5eb86 | 2004-02-07 21:13:00 +0000 | [diff] [blame] | 78 | \end{methoddesc} |
| 79 | |
| 80 | In addition to the above, deques support iteration, pickling, \samp{len(d)}, |
Raymond Hettinger | 0a4977c | 2004-03-01 23:16:22 +0000 | [diff] [blame] | 81 | \samp{reversed(d)}, \samp{copy.copy(d)}, \samp{copy.deepcopy(d)}, |
| 82 | membership testing with the \keyword{in} operator, and subscript references |
| 83 | such as \samp{d[-1]}. |
Raymond Hettinger | e52f3b1 | 2004-01-29 07:27:45 +0000 | [diff] [blame] | 84 | |
| 85 | Example: |
| 86 | |
| 87 | \begin{verbatim} |
| 88 | >>> from collections import deque |
Raymond Hettinger | 5c5eb86 | 2004-02-07 21:13:00 +0000 | [diff] [blame] | 89 | >>> d = deque('ghi') # make a new deque with three items |
| 90 | >>> for elem in d: # iterate over the deque's elements |
Raymond Hettinger | 738ec90 | 2004-02-29 02:15:56 +0000 | [diff] [blame] | 91 | ... print elem.upper() |
Raymond Hettinger | e52f3b1 | 2004-01-29 07:27:45 +0000 | [diff] [blame] | 92 | G |
| 93 | H |
| 94 | I |
Raymond Hettinger | 738ec90 | 2004-02-29 02:15:56 +0000 | [diff] [blame] | 95 | |
Raymond Hettinger | 5c5eb86 | 2004-02-07 21:13:00 +0000 | [diff] [blame] | 96 | >>> d.append('j') # add a new entry to the right side |
| 97 | >>> d.appendleft('f') # add a new entry to the left side |
| 98 | >>> d # show the representation of the deque |
Raymond Hettinger | e52f3b1 | 2004-01-29 07:27:45 +0000 | [diff] [blame] | 99 | deque(['f', 'g', 'h', 'i', 'j']) |
Raymond Hettinger | 738ec90 | 2004-02-29 02:15:56 +0000 | [diff] [blame] | 100 | |
Raymond Hettinger | 5c5eb86 | 2004-02-07 21:13:00 +0000 | [diff] [blame] | 101 | >>> d.pop() # return and remove the rightmost item |
Raymond Hettinger | e52f3b1 | 2004-01-29 07:27:45 +0000 | [diff] [blame] | 102 | 'j' |
Raymond Hettinger | 5c5eb86 | 2004-02-07 21:13:00 +0000 | [diff] [blame] | 103 | >>> d.popleft() # return and remove the leftmost item |
Raymond Hettinger | e52f3b1 | 2004-01-29 07:27:45 +0000 | [diff] [blame] | 104 | 'f' |
Raymond Hettinger | 5c5eb86 | 2004-02-07 21:13:00 +0000 | [diff] [blame] | 105 | >>> list(d) # list the contents of the deque |
Raymond Hettinger | e52f3b1 | 2004-01-29 07:27:45 +0000 | [diff] [blame] | 106 | ['g', 'h', 'i'] |
Raymond Hettinger | 0a4977c | 2004-03-01 23:16:22 +0000 | [diff] [blame] | 107 | >>> d[0] # peek at leftmost item |
Raymond Hettinger | 738ec90 | 2004-02-29 02:15:56 +0000 | [diff] [blame] | 108 | 'g' |
Raymond Hettinger | 0a4977c | 2004-03-01 23:16:22 +0000 | [diff] [blame] | 109 | >>> d[-1] # peek at rightmost item |
Raymond Hettinger | 738ec90 | 2004-02-29 02:15:56 +0000 | [diff] [blame] | 110 | 'i' |
Raymond Hettinger | 0a4977c | 2004-03-01 23:16:22 +0000 | [diff] [blame] | 111 | |
Raymond Hettinger | 5c5eb86 | 2004-02-07 21:13:00 +0000 | [diff] [blame] | 112 | >>> list(reversed(d)) # list the contents of a deque in reverse |
Raymond Hettinger | c058fd1 | 2004-02-07 02:45:22 +0000 | [diff] [blame] | 113 | ['i', 'h', 'g'] |
Raymond Hettinger | 5c5eb86 | 2004-02-07 21:13:00 +0000 | [diff] [blame] | 114 | >>> 'h' in d # search the deque |
Raymond Hettinger | e52f3b1 | 2004-01-29 07:27:45 +0000 | [diff] [blame] | 115 | True |
Raymond Hettinger | 5c5eb86 | 2004-02-07 21:13:00 +0000 | [diff] [blame] | 116 | >>> d.extend('jkl') # add multiple elements at once |
Raymond Hettinger | e52f3b1 | 2004-01-29 07:27:45 +0000 | [diff] [blame] | 117 | >>> d |
| 118 | deque(['g', 'h', 'i', 'j', 'k', 'l']) |
Raymond Hettinger | 5c5eb86 | 2004-02-07 21:13:00 +0000 | [diff] [blame] | 119 | >>> d.rotate(1) # right rotation |
| 120 | >>> d |
| 121 | deque(['l', 'g', 'h', 'i', 'j', 'k']) |
| 122 | >>> d.rotate(-1) # left rotation |
| 123 | >>> d |
| 124 | deque(['g', 'h', 'i', 'j', 'k', 'l']) |
Raymond Hettinger | 738ec90 | 2004-02-29 02:15:56 +0000 | [diff] [blame] | 125 | |
Raymond Hettinger | 5c5eb86 | 2004-02-07 21:13:00 +0000 | [diff] [blame] | 126 | >>> deque(reversed(d)) # make a new deque in reverse order |
| 127 | deque(['l', 'k', 'j', 'i', 'h', 'g']) |
| 128 | >>> d.clear() # empty the deque |
| 129 | >>> d.pop() # cannot pop from an empty deque |
Raymond Hettinger | e52f3b1 | 2004-01-29 07:27:45 +0000 | [diff] [blame] | 130 | Traceback (most recent call last): |
| 131 | File "<pyshell#6>", line 1, in -toplevel- |
| 132 | d.pop() |
Raymond Hettinger | 738ec90 | 2004-02-29 02:15:56 +0000 | [diff] [blame] | 133 | IndexError: pop from an empty deque |
Raymond Hettinger | 3ba85c2 | 2004-02-06 19:04:56 +0000 | [diff] [blame] | 134 | |
Raymond Hettinger | 5c5eb86 | 2004-02-07 21:13:00 +0000 | [diff] [blame] | 135 | >>> d.extendleft('abc') # extendleft() reverses the input order |
Raymond Hettinger | 3ba85c2 | 2004-02-06 19:04:56 +0000 | [diff] [blame] | 136 | >>> d |
| 137 | deque(['c', 'b', 'a']) |
Raymond Hettinger | f5f9a370 | 2004-04-30 22:52:50 +0000 | [diff] [blame] | 138 | \end{verbatim} |
Raymond Hettinger | 3ba85c2 | 2004-02-06 19:04:56 +0000 | [diff] [blame] | 139 | |
Raymond Hettinger | e7169eb | 2004-05-09 01:15:01 +0000 | [diff] [blame] | 140 | \subsection{Recipes \label{deque-recipes}} |
| 141 | |
| 142 | This section shows various approaches to working with deques. |
| 143 | |
| 144 | The \method{rotate()} method provides a way to implement \class{deque} |
Raymond Hettinger | 2e66940 | 2004-06-12 07:59:40 +0000 | [diff] [blame] | 145 | slicing and deletion. For example, a pure python implementation of |
| 146 | \code{del d[n]} relies on the \method{rotate()} method to position |
| 147 | elements to be popped: |
| 148 | |
Raymond Hettinger | e7169eb | 2004-05-09 01:15:01 +0000 | [diff] [blame] | 149 | \begin{verbatim} |
| 150 | def delete_nth(d, n): |
Raymond Hettinger | e7169eb | 2004-05-09 01:15:01 +0000 | [diff] [blame] | 151 | d.rotate(-n) |
| 152 | d.popleft() |
| 153 | d.rotate(n) |
Raymond Hettinger | e7169eb | 2004-05-09 01:15:01 +0000 | [diff] [blame] | 154 | \end{verbatim} |
| 155 | |
Raymond Hettinger | 0e371f2 | 2004-05-12 20:55:56 +0000 | [diff] [blame] | 156 | To implement \class{deque} slicing, use a similar approach applying |
| 157 | \method{rotate()} to bring a target element to the left side of the deque. |
| 158 | Remove old entries with \method{popleft()}, add new entries with |
| 159 | \method{extend()}, and then reverse the rotation. |
Raymond Hettinger | e7169eb | 2004-05-09 01:15:01 +0000 | [diff] [blame] | 160 | |
| 161 | With minor variations on that approach, it is easy to implement Forth style |
| 162 | stack manipulations such as \code{dup}, \code{drop}, \code{swap}, \code{over}, |
| 163 | \code{pick}, \code{rot}, and \code{roll}. |
Raymond Hettinger | f5f9a370 | 2004-04-30 22:52:50 +0000 | [diff] [blame] | 164 | |
| 165 | A roundrobin task server can be built from a \class{deque} using |
| 166 | \method{popleft()} to select the current task and \method{append()} |
| 167 | to add it back to the tasklist if the input stream is not exhausted: |
| 168 | |
| 169 | \begin{verbatim} |
| 170 | def roundrobin(*iterables): |
| 171 | pending = deque(iter(i) for i in iterables) |
| 172 | while pending: |
| 173 | task = pending.popleft() |
| 174 | try: |
| 175 | yield task.next() |
| 176 | except StopIteration: |
| 177 | continue |
| 178 | pending.append(task) |
| 179 | |
| 180 | >>> for value in roundrobin('abc', 'd', 'efgh'): |
Raymond Hettinger | e7169eb | 2004-05-09 01:15:01 +0000 | [diff] [blame] | 181 | ... print value |
Raymond Hettinger | f5f9a370 | 2004-04-30 22:52:50 +0000 | [diff] [blame] | 182 | |
| 183 | a |
| 184 | d |
| 185 | e |
| 186 | b |
| 187 | f |
| 188 | c |
| 189 | g |
| 190 | h |
| 191 | |
| 192 | \end{verbatim} |
Raymond Hettinger | e7169eb | 2004-05-09 01:15:01 +0000 | [diff] [blame] | 193 | |
| 194 | |
| 195 | Multi-pass data reduction algorithms can be succinctly expressed and |
Raymond Hettinger | 2e66940 | 2004-06-12 07:59:40 +0000 | [diff] [blame] | 196 | efficiently coded by extracting elements with multiple calls to |
| 197 | \method{popleft()}, applying the reduction function, and calling |
| 198 | \method{append()} to add the result back to the queue. |
Raymond Hettinger | e7169eb | 2004-05-09 01:15:01 +0000 | [diff] [blame] | 199 | |
| 200 | For example, building a balanced binary tree of nested lists entails |
| 201 | reducing two adjacent nodes into one by grouping them in a list: |
| 202 | |
| 203 | \begin{verbatim} |
| 204 | def maketree(iterable): |
| 205 | d = deque(iterable) |
| 206 | while len(d) > 1: |
| 207 | pair = [d.popleft(), d.popleft()] |
| 208 | d.append(pair) |
| 209 | return list(d) |
| 210 | |
| 211 | >>> print maketree('abcdefgh') |
| 212 | [[[['a', 'b'], ['c', 'd']], [['e', 'f'], ['g', 'h']]]] |
| 213 | |
| 214 | \end{verbatim} |
Guido van Rossum | 1968ad3 | 2006-02-25 22:38:04 +0000 | [diff] [blame] | 215 | |
| 216 | |
| 217 | |
| 218 | \begin{funcdesc}{defaultdict}{\optional{default_factory\optional{, ...}}} |
| 219 | Returns a new dictionary-like object. \class{defaultdict} is a subclass |
| 220 | of the builtin \class{dict} class. It overrides one method and adds one |
| 221 | writable instance variable. The remaining functionality is the same as |
| 222 | for the \class{dict} class and is not documented here. |
| 223 | |
| 224 | The first argument provides the initial value for the |
| 225 | \member{default_factory} attribute; it defaults to \code{None}. |
| 226 | All remaining arguments are treated the same as if they were |
| 227 | passed to the \class{dict} constructor, including keyword arguments. |
| 228 | |
| 229 | \versionadded{2.5} |
| 230 | \end{funcdesc} |
| 231 | |
| 232 | \class{defaultdict} objects support the following method in addition to |
| 233 | the standard \class{dict} operations: |
| 234 | |
| 235 | \begin{methoddesc}{__missing__}{key} |
| 236 | If the \member{default_factory} attribute is \code{None}, this raises |
| 237 | an \exception{KeyError} exception with the \var{key} as argument. |
| 238 | |
| 239 | If \member{default_factory} is not \code{None}, it is called without |
| 240 | arguments to provide a default value for the given \var{key}, this |
| 241 | value is inserted in the dictionary for the \var{key}, and returned. |
| 242 | |
| 243 | If calling \member{default_factory} raises an exception this exception |
| 244 | is propagated unchanged. |
| 245 | |
| 246 | This method is called by the \method{__getitem__} method of the |
| 247 | \class{dict} class when the requested key is not found; whatever it |
| 248 | returns or raises is then returned or raised by \method{__getitem__}. |
| 249 | \end{methoddesc} |
| 250 | |
| 251 | \class{defaultdict} objects support the following instance variable: |
| 252 | |
| 253 | \begin{datadesc}{default_factory} |
| 254 | This attribute is used by the \method{__missing__} method; it is initialized |
| 255 | from the first argument to the constructor, if present, or to \code{None}, |
| 256 | if absent. |
| 257 | \end{datadesc} |