blob: 51603aa23373cf622ce4e5aaee89d033a2acb125 [file] [log] [blame]
Raymond Hettingere52f3b12004-01-29 07:27:45 +00001\section{\module{collections} ---
Raymond Hettinger5c5eb862004-02-07 21:13:00 +00002 High-performance container datatypes}
Raymond Hettingere52f3b12004-01-29 07:27:45 +00003
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
Raymond Hettinger5c5eb862004-02-07 21:13:00 +000011This module implements high-performance container datatypes. Currently, the
Raymond Hettingere52f3b12004-01-29 07:27:45 +000012only datatype is a deque. Future additions may include B-trees
13and Fibonacci heaps.
14
15\begin{funcdesc}{deque}{\optional{iterable}}
16 Returns a new deque objected initialized left-to-right (using
17 \method{append()}) with data from \var{iterable}. If \var{iterable}
18 is not specified, the new deque is empty.
19
Raymond Hettinger5c5eb862004-02-07 21:13:00 +000020 Deques are a generalization of stacks and queues (the name is pronounced
21 ``deck'' and is short for ``double-ended queue''). Deques support
22 thread-safe, memory efficient appends and pops from either side of the deque
23 with approximately the same \code{O(1)} performance in either direction.
24
25 Though \class{list} objects support similar operations, they are optimized
26 for fast fixed-length operations and incur \code{O(n)} memory movement costs
27 for \samp{pop(0)} and \samp{insert(0, v)} operations which change both the
28 size and position of the underlying data representation.
Raymond Hettingere52f3b12004-01-29 07:27:45 +000029 \versionadded{2.4}
30\end{funcdesc}
31
32Deque objects support the following methods:
33
34\begin{methoddesc}{append}{x}
35 Add \var{x} to the right side of the deque.
36\end{methoddesc}
37
38\begin{methoddesc}{appendleft}{x}
39 Add \var{x} to the left side of the deque.
40\end{methoddesc}
41
42\begin{methoddesc}{clear}{}
43 Remove all elements from the deque leaving it with length 0.
44\end{methoddesc}
45
Raymond Hettinger3ba85c22004-02-06 19:04:56 +000046\begin{methoddesc}{extend}{iterable}
47 Extend the right side of the deque by appending elements from
48 the iterable argument.
49\end{methoddesc}
50
51\begin{methoddesc}{extendleft}{iterable}
52 Extend the left side of the deque by appending elements from
53 \var{iterable}. Note, the series of left appends results in
54 reversing the order of elements in the iterable argument.
55\end{methoddesc}
56
Raymond Hettingere52f3b12004-01-29 07:27:45 +000057\begin{methoddesc}{pop}{}
58 Remove and return an element from the right side of the deque.
Raymond Hettinger738ec902004-02-29 02:15:56 +000059 If no elements are present, raises a \exception{IndexError}.
Raymond Hettingere52f3b12004-01-29 07:27:45 +000060\end{methoddesc}
61
62\begin{methoddesc}{popleft}{}
63 Remove and return an element from the left side of the deque.
Raymond Hettinger738ec902004-02-29 02:15:56 +000064 If no elements are present, raises a \exception{IndexError}.
65\end{methoddesc}
66
Raymond Hettinger4aec61e2005-03-18 21:20:23 +000067\begin{methoddesc}{remove}{value}
68 Removed the first occurrence of \var{value}. If not found,
69 raises a \exception{ValueError}.
70 \versionadded{2.5}
71\end{methoddesc}
72
Raymond Hettinger5c5eb862004-02-07 21:13:00 +000073\begin{methoddesc}{rotate}{n}
74 Rotate the deque \var{n} steps to the right. If \var{n} is
75 negative, rotate to the left. Rotating one step to the right
Raymond Hettingerf5f9a3702004-04-30 22:52:50 +000076 is equivalent to: \samp{d.appendleft(d.pop())}.
Raymond Hettinger5c5eb862004-02-07 21:13:00 +000077\end{methoddesc}
78
79In addition to the above, deques support iteration, pickling, \samp{len(d)},
Raymond Hettinger0a4977c2004-03-01 23:16:22 +000080\samp{reversed(d)}, \samp{copy.copy(d)}, \samp{copy.deepcopy(d)},
81membership testing with the \keyword{in} operator, and subscript references
82such as \samp{d[-1]}.
Raymond Hettingere52f3b12004-01-29 07:27:45 +000083
84Example:
85
86\begin{verbatim}
87>>> from collections import deque
Raymond Hettinger5c5eb862004-02-07 21:13:00 +000088>>> d = deque('ghi') # make a new deque with three items
89>>> for elem in d: # iterate over the deque's elements
Raymond Hettinger738ec902004-02-29 02:15:56 +000090... print elem.upper()
Raymond Hettingere52f3b12004-01-29 07:27:45 +000091G
92H
93I
Raymond Hettinger738ec902004-02-29 02:15:56 +000094
Raymond Hettinger5c5eb862004-02-07 21:13:00 +000095>>> d.append('j') # add a new entry to the right side
96>>> d.appendleft('f') # add a new entry to the left side
97>>> d # show the representation of the deque
Raymond Hettingere52f3b12004-01-29 07:27:45 +000098deque(['f', 'g', 'h', 'i', 'j'])
Raymond Hettinger738ec902004-02-29 02:15:56 +000099
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000100>>> d.pop() # return and remove the rightmost item
Raymond Hettingere52f3b12004-01-29 07:27:45 +0000101'j'
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000102>>> d.popleft() # return and remove the leftmost item
Raymond Hettingere52f3b12004-01-29 07:27:45 +0000103'f'
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000104>>> list(d) # list the contents of the deque
Raymond Hettingere52f3b12004-01-29 07:27:45 +0000105['g', 'h', 'i']
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000106>>> d[0] # peek at leftmost item
Raymond Hettinger738ec902004-02-29 02:15:56 +0000107'g'
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000108>>> d[-1] # peek at rightmost item
Raymond Hettinger738ec902004-02-29 02:15:56 +0000109'i'
Raymond Hettinger0a4977c2004-03-01 23:16:22 +0000110
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000111>>> list(reversed(d)) # list the contents of a deque in reverse
Raymond Hettingerc058fd12004-02-07 02:45:22 +0000112['i', 'h', 'g']
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000113>>> 'h' in d # search the deque
Raymond Hettingere52f3b12004-01-29 07:27:45 +0000114True
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000115>>> d.extend('jkl') # add multiple elements at once
Raymond Hettingere52f3b12004-01-29 07:27:45 +0000116>>> d
117deque(['g', 'h', 'i', 'j', 'k', 'l'])
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000118>>> d.rotate(1) # right rotation
119>>> d
120deque(['l', 'g', 'h', 'i', 'j', 'k'])
121>>> d.rotate(-1) # left rotation
122>>> d
123deque(['g', 'h', 'i', 'j', 'k', 'l'])
Raymond Hettinger738ec902004-02-29 02:15:56 +0000124
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000125>>> deque(reversed(d)) # make a new deque in reverse order
126deque(['l', 'k', 'j', 'i', 'h', 'g'])
127>>> d.clear() # empty the deque
128>>> d.pop() # cannot pop from an empty deque
Raymond Hettingere52f3b12004-01-29 07:27:45 +0000129Traceback (most recent call last):
130 File "<pyshell#6>", line 1, in -toplevel-
131 d.pop()
Raymond Hettinger738ec902004-02-29 02:15:56 +0000132IndexError: pop from an empty deque
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000133
Raymond Hettinger5c5eb862004-02-07 21:13:00 +0000134>>> d.extendleft('abc') # extendleft() reverses the input order
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000135>>> d
136deque(['c', 'b', 'a'])
Raymond Hettingerf5f9a3702004-04-30 22:52:50 +0000137\end{verbatim}
Raymond Hettinger3ba85c22004-02-06 19:04:56 +0000138
Raymond Hettingere7169eb2004-05-09 01:15:01 +0000139\subsection{Recipes \label{deque-recipes}}
140
141This section shows various approaches to working with deques.
142
143The \method{rotate()} method provides a way to implement \class{deque}
Raymond Hettinger2e669402004-06-12 07:59:40 +0000144slicing and deletion. For example, a pure python implementation of
145\code{del d[n]} relies on the \method{rotate()} method to position
146elements to be popped:
147
Raymond Hettingere7169eb2004-05-09 01:15:01 +0000148\begin{verbatim}
149def delete_nth(d, n):
Raymond Hettingere7169eb2004-05-09 01:15:01 +0000150 d.rotate(-n)
151 d.popleft()
152 d.rotate(n)
Raymond Hettingere7169eb2004-05-09 01:15:01 +0000153\end{verbatim}
154
Raymond Hettinger0e371f22004-05-12 20:55:56 +0000155To implement \class{deque} slicing, use a similar approach applying
156\method{rotate()} to bring a target element to the left side of the deque.
157Remove old entries with \method{popleft()}, add new entries with
158\method{extend()}, and then reverse the rotation.
Raymond Hettingere7169eb2004-05-09 01:15:01 +0000159
160With minor variations on that approach, it is easy to implement Forth style
161stack manipulations such as \code{dup}, \code{drop}, \code{swap}, \code{over},
162\code{pick}, \code{rot}, and \code{roll}.
Raymond Hettingerf5f9a3702004-04-30 22:52:50 +0000163
164A roundrobin task server can be built from a \class{deque} using
165\method{popleft()} to select the current task and \method{append()}
166to add it back to the tasklist if the input stream is not exhausted:
167
168\begin{verbatim}
169def roundrobin(*iterables):
170 pending = deque(iter(i) for i in iterables)
171 while pending:
172 task = pending.popleft()
173 try:
174 yield task.next()
175 except StopIteration:
176 continue
177 pending.append(task)
178
179>>> for value in roundrobin('abc', 'd', 'efgh'):
Raymond Hettingere7169eb2004-05-09 01:15:01 +0000180... print value
Raymond Hettingerf5f9a3702004-04-30 22:52:50 +0000181
182a
183d
184e
185b
186f
187c
188g
189h
190
191\end{verbatim}
Raymond Hettingere7169eb2004-05-09 01:15:01 +0000192
193
194Multi-pass data reduction algorithms can be succinctly expressed and
Raymond Hettinger2e669402004-06-12 07:59:40 +0000195efficiently coded by extracting elements with multiple calls to
196\method{popleft()}, applying the reduction function, and calling
197\method{append()} to add the result back to the queue.
Raymond Hettingere7169eb2004-05-09 01:15:01 +0000198
199For example, building a balanced binary tree of nested lists entails
200reducing two adjacent nodes into one by grouping them in a list:
201
202\begin{verbatim}
203def maketree(iterable):
204 d = deque(iterable)
205 while len(d) > 1:
206 pair = [d.popleft(), d.popleft()]
207 d.append(pair)
208 return list(d)
209
210>>> print maketree('abcdefgh')
211[[[['a', 'b'], ['c', 'd']], [['e', 'f'], ['g', 'h']]]]
212
213\end{verbatim}