blob: e6ccd7ab145ffe21b4cec958d88fc4e413aea4df [file] [log] [blame]
Raymond Hettingere52f3b12004-01-29 07:27:45 +00001\section{\module{collections} ---
2 High-performance datatypes}
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
11This module implements high-performance datatypes. Currently, the
12only 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
20 Deques are a generalization of stacks and queues. They support
21 thread-safe, memory efficient appends and pops from either side of the
22 deque with approximately the same performance in either direction.
23 \versionadded{2.4}
24\end{funcdesc}
25
26Deque objects support the following methods:
27
28\begin{methoddesc}{append}{x}
29 Add \var{x} to the right side of the deque.
30\end{methoddesc}
31
32\begin{methoddesc}{appendleft}{x}
33 Add \var{x} to the left side of the deque.
34\end{methoddesc}
35
36\begin{methoddesc}{clear}{}
37 Remove all elements from the deque leaving it with length 0.
38\end{methoddesc}
39
40\begin{methoddesc}{pop}{}
41 Remove and return an element from the right side of the deque.
42 If no elements are present, raises a \exception{LookupError}.
43\end{methoddesc}
44
45\begin{methoddesc}{popleft}{}
46 Remove and return an element from the left side of the deque.
47 If no elements are present, raises a \exception{LookupError}.
48\end{methoddesc}
49
50In addition to the above, deques support iteration, membership testing
51using the \keyword{in} operator, \samp{len(d)}, \samp{copy.copy(d)},
52\samp{copy.deepcopy(d)}, and pickling.
53
54Example:
55
56\begin{verbatim}
57>>> from collections import deque
58>>> d = deque('ghi') # make a new deque with three items
59>>> for elem in d: # iterate over the deque's elements
60 print elem.upper()
61
62
63G
64H
65I
66>>> d.append('j') # add a new entry to the right side
67>>> d.appendleft('f') # add a new entry to the left side
68>>> d # show the representation of the deque
69deque(['f', 'g', 'h', 'i', 'j'])
70>>> d.pop() # return and remove the rightmost item
71'j'
72>>> d.popleft() # return and remove the leftmost item
73'f'
74>>> list(d) # list the contents of the deque
75['g', 'h', 'i']
76>>> 'h' in d # search the deque
77True
78>>> d.__init__('jkl') # use __init__ to append many elements at once
79>>> d
80deque(['g', 'h', 'i', 'j', 'k', 'l'])
81>>> d.clear() # empty the deque
82>>> d.pop() # try to pop from an empty deque
83
84Traceback (most recent call last):
85 File "<pyshell#6>", line 1, in -toplevel-
86 d.pop()
87LookupError: pop from an empty deque
88\end{verbatim}