blob: 19bc826e772dc1bb43197f356f071a5c806275b5 [file] [log] [blame]
Raymond Hettinger96ef8112003-02-01 00:10:11 +00001\section{\module{itertools} ---
2 Functions creating iterators for efficient looping}
3
4\declaremodule{standard}{itertools}
5\modulesynopsis{Functions creating iterators for efficient looping.}
6\moduleauthor{Raymond Hettinger}{python@rcn.com}
7\sectionauthor{Raymond Hettinger}{python@rcn.com}
8\versionadded{2.3}
9
10
11This module implements a number of iterator building blocks inspired
12by constructs from the Haskell and SML programming languages. Each
13has been recast in a form suitable for Python.
14
Raymond Hettinger60eca932003-02-09 06:40:58 +000015The module standardizes a core set of fast, memory efficient tools
16that are useful by themselves or in combination. Standardization helps
17avoid the readability and reliability problems which arise when many
18different individuals create their own slightly varying implementations,
19each with their own quirks and naming conventions.
Raymond Hettinger96ef8112003-02-01 00:10:11 +000020
Raymond Hettinger1b18ba42003-02-21 01:45:34 +000021The tools are designed to combine readily with one another. This makes
Raymond Hettinger60eca932003-02-09 06:40:58 +000022it easy to construct more specialized tools succinctly and efficiently
23in pure Python.
Raymond Hettinger96ef8112003-02-01 00:10:11 +000024
Raymond Hettinger1b18ba42003-02-21 01:45:34 +000025For instance, SML provides a tabulation tool: \code{tabulate(f)}
Raymond Hettinger60eca932003-02-09 06:40:58 +000026which produces a sequence \code{f(0), f(1), ...}. This toolbox
27provides \function{imap()} and \function{count()} which can be combined
Raymond Hettinger1b18ba42003-02-21 01:45:34 +000028to form \code{imap(f, count())} and produce an equivalent result.
Raymond Hettinger96ef8112003-02-01 00:10:11 +000029
Raymond Hettinger863983e2003-04-23 00:09:42 +000030Likewise, the functional tools are designed to work well with the
31high-speed functions provided by the \refmodule{operator} module.
32
33The module author welcomes suggestions for other basic building blocks
34to be added to future versions of the module.
35
Raymond Hettingerd7911a32004-05-01 08:31:36 +000036Whether cast in pure python form or compiled code, tools that use iterators
Raymond Hettinger60eca932003-02-09 06:40:58 +000037are more memory efficient (and faster) than their list based counterparts.
38Adopting the principles of just-in-time manufacturing, they create
39data when and where needed instead of consuming memory with the
40computer equivalent of ``inventory''.
Raymond Hettinger96ef8112003-02-01 00:10:11 +000041
Raymond Hettinger863983e2003-04-23 00:09:42 +000042The performance advantage of iterators becomes more acute as the number
43of elements increases -- at some point, lists grow large enough to
Raymond Hettinger7e431102003-09-22 15:00:55 +000044severely impact memory cache performance and start running slowly.
Raymond Hettinger96ef8112003-02-01 00:10:11 +000045
46\begin{seealso}
47 \seetext{The Standard ML Basis Library,
48 \citetitle[http://www.standardml.org/Basis/]
49 {The Standard ML Basis Library}.}
50
51 \seetext{Haskell, A Purely Functional Language,
52 \citetitle[http://www.haskell.org/definition/]
53 {Definition of Haskell and the Standard Libraries}.}
54\end{seealso}
55
56
57\subsection{Itertool functions \label{itertools-functions}}
58
59The following module functions all construct and return iterators.
60Some provide streams of infinite length, so they should only be accessed
61by functions or loops that truncate the stream.
62
Raymond Hettinger61fe64d2003-02-23 04:40:07 +000063\begin{funcdesc}{chain}{*iterables}
64 Make an iterator that returns elements from the first iterable until
65 it is exhausted, then proceeds to the next iterable, until all of the
66 iterables are exhausted. Used for treating consecutive sequences as
67 a single sequence. Equivalent to:
68
69 \begin{verbatim}
70 def chain(*iterables):
71 for it in iterables:
72 for element in it:
73 yield element
74 \end{verbatim}
75\end{funcdesc}
76
Raymond Hettinger96ef8112003-02-01 00:10:11 +000077\begin{funcdesc}{count}{\optional{n}}
78 Make an iterator that returns consecutive integers starting with \var{n}.
Raymond Hettingerff294fe2003-12-07 13:00:25 +000079 If not specified \var{n} defaults to zero.
Raymond Hettinger96ef8112003-02-01 00:10:11 +000080 Does not currently support python long integers. Often used as an
81 argument to \function{imap()} to generate consecutive data points.
Raymond Hettingerc7d77662003-08-08 02:40:28 +000082 Also, used with \function{izip()} to add sequence numbers. Equivalent to:
Raymond Hettinger96ef8112003-02-01 00:10:11 +000083
84 \begin{verbatim}
85 def count(n=0):
Raymond Hettinger96ef8112003-02-01 00:10:11 +000086 while True:
Raymond Hettinger1b18ba42003-02-21 01:45:34 +000087 yield n
88 n += 1
Raymond Hettinger96ef8112003-02-01 00:10:11 +000089 \end{verbatim}
Raymond Hettinger2012f172003-02-07 05:32:58 +000090
91 Note, \function{count()} does not check for overflow and will return
92 negative numbers after exceeding \code{sys.maxint}. This behavior
93 may change in the future.
Raymond Hettinger96ef8112003-02-01 00:10:11 +000094\end{funcdesc}
95
Raymond Hettinger61fe64d2003-02-23 04:40:07 +000096\begin{funcdesc}{cycle}{iterable}
97 Make an iterator returning elements from the iterable and saving a
98 copy of each. When the iterable is exhausted, return elements from
99 the saved copy. Repeats indefinitely. Equivalent to:
100
101 \begin{verbatim}
102 def cycle(iterable):
103 saved = []
104 for element in iterable:
105 yield element
106 saved.append(element)
Raymond Hettingerc7d77662003-08-08 02:40:28 +0000107 while saved:
Raymond Hettinger61fe64d2003-02-23 04:40:07 +0000108 for element in saved:
109 yield element
110 \end{verbatim}
111
Raymond Hettinger6a5b0272003-10-24 08:45:23 +0000112 Note, this member of the toolkit may require significant
113 auxiliary storage (depending on the length of the iterable).
Raymond Hettinger61fe64d2003-02-23 04:40:07 +0000114\end{funcdesc}
115
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000116\begin{funcdesc}{dropwhile}{predicate, iterable}
117 Make an iterator that drops elements from the iterable as long as
118 the predicate is true; afterwards, returns every element. Note,
119 the iterator does not produce \emph{any} output until the predicate
120 is true, so it may have a lengthy start-up time. Equivalent to:
121
122 \begin{verbatim}
123 def dropwhile(predicate, iterable):
124 iterable = iter(iterable)
Raymond Hettingerc7d77662003-08-08 02:40:28 +0000125 for x in iterable:
126 if not predicate(x):
127 yield x
128 break
129 for x in iterable:
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000130 yield x
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000131 \end{verbatim}
132\end{funcdesc}
133
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000134\begin{funcdesc}{groupby}{iterable\optional{, key}}
135 Make an iterator that returns consecutive keys and groups from the
Raymond Hettinger88e8e342004-07-11 13:20:11 +0000136 \var{iterable}. The \var{key} is a function computing a key value for each
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000137 element. If not specified or is \code{None}, \var{key} defaults to an
Andrew M. Kuchlingdb7dcff2003-12-06 22:29:43 +0000138 identity function and returns the element unchanged. Generally, the
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000139 iterable needs to already be sorted on the same key function.
140
Guido van Rossume7ba4952007-06-06 23:52:48 +0000141 The operation of \function{groupby()} is similar to the \code{uniq} filter
142 in \UNIX{}. It generates a break or new group every time the value
143 of the key function changes (which is why it is usually necessary
144 to have sorted the data using the same key function). That behavior
145 differs from SQL's GROUP BY which aggregates common elements regardless
146 of their input order.
147
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000148 The returned group is itself an iterator that shares the underlying
149 iterable with \function{groupby()}. Because the source is shared, when
150 the \function{groupby} object is advanced, the previous group is no
151 longer visible. So, if that data is needed later, it should be stored
152 as a list:
153
154 \begin{verbatim}
155 groups = []
156 uniquekeys = []
Guido van Rossume7ba4952007-06-06 23:52:48 +0000157 data = sorted(data, key=keyfunc)
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000158 for k, g in groupby(data, keyfunc):
159 groups.append(list(g)) # Store group iterator as a list
160 uniquekeys.append(k)
161 \end{verbatim}
162
163 \function{groupby()} is equivalent to:
164
165 \begin{verbatim}
166 class groupby(object):
167 def __init__(self, iterable, key=None):
168 if key is None:
169 key = lambda x: x
170 self.keyfunc = key
171 self.it = iter(iterable)
Guido van Rossum805365e2007-05-07 22:24:25 +0000172 self.tgtkey = self.currkey = self.currvalue = []
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000173 def __iter__(self):
174 return self
Georg Brandla18af4e2007-04-21 15:47:16 +0000175 def __next__(self):
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000176 while self.currkey == self.tgtkey:
Georg Brandla18af4e2007-04-21 15:47:16 +0000177 self.currvalue = next(self.it) # Exit on StopIteration
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000178 self.currkey = self.keyfunc(self.currvalue)
179 self.tgtkey = self.currkey
180 return (self.currkey, self._grouper(self.tgtkey))
181 def _grouper(self, tgtkey):
182 while self.currkey == tgtkey:
183 yield self.currvalue
Georg Brandla18af4e2007-04-21 15:47:16 +0000184 self.currvalue = next(self.it) # Exit on StopIteration
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000185 self.currkey = self.keyfunc(self.currvalue)
186 \end{verbatim}
187 \versionadded{2.4}
188\end{funcdesc}
189
Raymond Hettinger60eca932003-02-09 06:40:58 +0000190\begin{funcdesc}{ifilter}{predicate, iterable}
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000191 Make an iterator that filters elements from iterable returning only
Raymond Hettinger60eca932003-02-09 06:40:58 +0000192 those for which the predicate is \code{True}.
193 If \var{predicate} is \code{None}, return the items that are true.
194 Equivalent to:
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000195
196 \begin{verbatim}
Raymond Hettinger60eca932003-02-09 06:40:58 +0000197 def ifilter(predicate, iterable):
198 if predicate is None:
Guido van Rossum0c9a3182003-10-20 17:01:07 +0000199 predicate = bool
Raymond Hettinger60eca932003-02-09 06:40:58 +0000200 for x in iterable:
201 if predicate(x):
202 yield x
203 \end{verbatim}
204\end{funcdesc}
205
206\begin{funcdesc}{ifilterfalse}{predicate, iterable}
207 Make an iterator that filters elements from iterable returning only
208 those for which the predicate is \code{False}.
209 If \var{predicate} is \code{None}, return the items that are false.
210 Equivalent to:
211
212 \begin{verbatim}
213 def ifilterfalse(predicate, iterable):
214 if predicate is None:
Guido van Rossum0c9a3182003-10-20 17:01:07 +0000215 predicate = bool
Raymond Hettinger60eca932003-02-09 06:40:58 +0000216 for x in iterable:
217 if not predicate(x):
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000218 yield x
219 \end{verbatim}
220\end{funcdesc}
221
222\begin{funcdesc}{imap}{function, *iterables}
223 Make an iterator that computes the function using arguments from
224 each of the iterables. If \var{function} is set to \code{None}, then
225 \function{imap()} returns the arguments as a tuple. Like
226 \function{map()} but stops when the shortest iterable is exhausted
227 instead of filling in \code{None} for shorter iterables. The reason
228 for the difference is that infinite iterator arguments are typically
229 an error for \function{map()} (because the output is fully evaluated)
230 but represent a common and useful way of supplying arguments to
231 \function{imap()}.
232 Equivalent to:
233
234 \begin{verbatim}
235 def imap(function, *iterables):
236 iterables = map(iter, iterables)
237 while True:
Georg Brandla18af4e2007-04-21 15:47:16 +0000238 args = [next(i) for i in iterables]
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000239 if function is None:
240 yield tuple(args)
241 else:
242 yield function(*args)
243 \end{verbatim}
244\end{funcdesc}
245
246\begin{funcdesc}{islice}{iterable, \optional{start,} stop \optional{, step}}
247 Make an iterator that returns selected elements from the iterable.
248 If \var{start} is non-zero, then elements from the iterable are skipped
249 until start is reached. Afterward, elements are returned consecutively
250 unless \var{step} is set higher than one which results in items being
Raymond Hettinger341deb72003-05-02 19:44:20 +0000251 skipped. If \var{stop} is \code{None}, then iteration continues until
252 the iterator is exhausted, if at all; otherwise, it stops at the specified
253 position. Unlike regular slicing,
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000254 \function{islice()} does not support negative values for \var{start},
255 \var{stop}, or \var{step}. Can be used to extract related fields
256 from data where the internal structure has been flattened (for
257 example, a multi-line report may list a name field on every
258 third line). Equivalent to:
259
260 \begin{verbatim}
Raymond Hettinger1b2e0d92005-03-27 20:19:05 +0000261 def islice(iterable, *args):
Raymond Hettinger341deb72003-05-02 19:44:20 +0000262 s = slice(*args)
Guido van Rossum805365e2007-05-07 22:24:25 +0000263 it = iter(range(s.start or 0, s.stop or sys.maxint, s.step or 1))
Georg Brandla18af4e2007-04-21 15:47:16 +0000264 nexti = next(it)
Raymond Hettingerfdf3bd62005-03-27 20:11:44 +0000265 for i, element in enumerate(iterable):
266 if i == nexti:
267 yield element
Georg Brandla18af4e2007-04-21 15:47:16 +0000268 nexti = next(it)
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000269 \end{verbatim}
Raymond Hettingerb2594052004-12-05 09:25:51 +0000270
271 If \var{start} is \code{None}, then iteration starts at zero.
272 If \var{step} is \code{None}, then the step defaults to one.
273 \versionchanged[accept \code{None} values for default \var{start} and
274 \var{step}]{2.5}
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000275\end{funcdesc}
276
277\begin{funcdesc}{izip}{*iterables}
278 Make an iterator that aggregates elements from each of the iterables.
279 Like \function{zip()} except that it returns an iterator instead of
280 a list. Used for lock-step iteration over several iterables at a
281 time. Equivalent to:
282
283 \begin{verbatim}
284 def izip(*iterables):
285 iterables = map(iter, iterables)
Raymond Hettingerb5a42082003-08-08 05:10:41 +0000286 while iterables:
Georg Brandla18af4e2007-04-21 15:47:16 +0000287 result = [next(it) for it in iterables]
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000288 yield tuple(result)
289 \end{verbatim}
Raymond Hettingerb5a42082003-08-08 05:10:41 +0000290
291 \versionchanged[When no iterables are specified, returns a zero length
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000292 iterator instead of raising a \exception{TypeError}
293 exception]{2.4}
294
295 Note, the left-to-right evaluation order of the iterables is guaranteed.
296 This makes possible an idiom for clustering a data series into n-length
297 groups using \samp{izip(*[iter(s)]*n)}. For data that doesn't fit
298 n-length groups exactly, the last tuple can be pre-padded with fill
299 values using \samp{izip(*[chain(s, [None]*(n-1))]*n)}.
300
301 Note, when \function{izip()} is used with unequal length inputs, subsequent
302 iteration over the longer iterables cannot reliably be continued after
303 \function{izip()} terminates. Potentially, up to one entry will be missing
304 from each of the left-over iterables. This occurs because a value is fetched
305 from each iterator in-turn, but the process ends when one of the iterators
306 terminates. This leaves the last fetched values in limbo (they cannot be
307 returned in a final, incomplete tuple and they are cannot be pushed back
Georg Brandla18af4e2007-04-21 15:47:16 +0000308 into the iterator for retrieval with \code{next(it)}). In general,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000309 \function{izip()} should only be used with unequal length inputs when you
310 don't care about trailing, unmatched values from the longer iterables.
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000311\end{funcdesc}
312
Thomas Wouterscf297e42007-02-23 15:07:44 +0000313\begin{funcdesc}{izip_longest}{*iterables\optional{, fillvalue}}
314 Make an iterator that aggregates elements from each of the iterables.
315 If the iterables are of uneven length, missing values are filled-in
316 with \var{fillvalue}. Iteration continues until the longest iterable
317 is exhausted. Equivalent to:
318
319 \begin{verbatim}
320 def izip_longest(*args, **kwds):
321 fillvalue = kwds.get('fillvalue')
322 def sentinel(counter = ([fillvalue]*(len(args)-1)).pop):
323 yield counter() # yields the fillvalue, or raises IndexError
324 fillers = repeat(fillvalue)
325 iters = [chain(it, sentinel(), fillers) for it in args]
326 try:
327 for tup in izip(*iters):
328 yield tup
329 except IndexError:
330 pass
331 \end{verbatim}
332
333 If one of the iterables is potentially infinite, then the
334 \function{izip_longest()} function should be wrapped with something
335 that limits the number of calls (for example \function{islice()} or
336 \function{take()}).
337 \versionadded{2.6}
338\end{funcdesc}
339
Raymond Hettinger61fe64d2003-02-23 04:40:07 +0000340\begin{funcdesc}{repeat}{object\optional{, times}}
Raymond Hettinger1b18ba42003-02-21 01:45:34 +0000341 Make an iterator that returns \var{object} over and over again.
Raymond Hettinger61fe64d2003-02-23 04:40:07 +0000342 Runs indefinitely unless the \var{times} argument is specified.
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000343 Used as argument to \function{imap()} for invariant parameters
Raymond Hettinger1b18ba42003-02-21 01:45:34 +0000344 to the called function. Also used with \function{izip()} to create
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000345 an invariant part of a tuple record. Equivalent to:
346
347 \begin{verbatim}
Raymond Hettinger61fe64d2003-02-23 04:40:07 +0000348 def repeat(object, times=None):
349 if times is None:
350 while True:
351 yield object
352 else:
Guido van Rossum805365e2007-05-07 22:24:25 +0000353 for i in range(times):
Raymond Hettinger61fe64d2003-02-23 04:40:07 +0000354 yield object
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000355 \end{verbatim}
356\end{funcdesc}
357
358\begin{funcdesc}{starmap}{function, iterable}
359 Make an iterator that computes the function using arguments tuples
360 obtained from the iterable. Used instead of \function{imap()} when
361 argument parameters are already grouped in tuples from a single iterable
362 (the data has been ``pre-zipped''). The difference between
Raymond Hettinger1b18ba42003-02-21 01:45:34 +0000363 \function{imap()} and \function{starmap()} parallels the distinction
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000364 between \code{function(a,b)} and \code{function(*c)}.
365 Equivalent to:
366
367 \begin{verbatim}
368 def starmap(function, iterable):
369 iterable = iter(iterable)
370 while True:
Georg Brandla18af4e2007-04-21 15:47:16 +0000371 yield function(*next(iterable))
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000372 \end{verbatim}
373\end{funcdesc}
374
375\begin{funcdesc}{takewhile}{predicate, iterable}
376 Make an iterator that returns elements from the iterable as long as
377 the predicate is true. Equivalent to:
378
379 \begin{verbatim}
380 def takewhile(predicate, iterable):
Raymond Hettingerc7d77662003-08-08 02:40:28 +0000381 for x in iterable:
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000382 if predicate(x):
383 yield x
384 else:
385 break
386 \end{verbatim}
387\end{funcdesc}
388
Raymond Hettingerad983e72003-11-12 14:32:26 +0000389\begin{funcdesc}{tee}{iterable\optional{, n=2}}
390 Return \var{n} independent iterators from a single iterable.
Raymond Hettinger88e8e342004-07-11 13:20:11 +0000391 The case where \code{n==2} is equivalent to:
Raymond Hettinger6a5b0272003-10-24 08:45:23 +0000392
393 \begin{verbatim}
394 def tee(iterable):
395 def gen(next, data={}, cnt=[0]):
396 for i in count():
397 if i == cnt[0]:
398 item = data[i] = next()
399 cnt[0] += 1
400 else:
401 item = data.pop(i)
402 yield item
403 it = iter(iterable)
Georg Brandla18af4e2007-04-21 15:47:16 +0000404 return (gen(it.__next__), gen(it.__next__))
Raymond Hettinger6a5b0272003-10-24 08:45:23 +0000405 \end{verbatim}
406
Raymond Hettingerad983e72003-11-12 14:32:26 +0000407 Note, once \function{tee()} has made a split, the original \var{iterable}
408 should not be used anywhere else; otherwise, the \var{iterable} could get
409 advanced without the tee objects being informed.
410
Raymond Hettinger6a5b0272003-10-24 08:45:23 +0000411 Note, this member of the toolkit may require significant auxiliary
412 storage (depending on how much temporary data needs to be stored).
Andrew M. Kuchling34358202003-12-18 13:28:35 +0000413 In general, if one iterator is going to use most or all of the data before
Raymond Hettinger6a5b0272003-10-24 08:45:23 +0000414 the other iterator, it is faster to use \function{list()} instead of
415 \function{tee()}.
416 \versionadded{2.4}
417\end{funcdesc}
418
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000419
420\subsection{Examples \label{itertools-example}}
421
422The following examples show common uses for each tool and
423demonstrate ways they can be combined.
424
425\begin{verbatim}
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000426
427>>> amounts = [120.15, 764.05, 823.14]
428>>> for checknum, amount in izip(count(1200), amounts):
429... print 'Check %d is for $%.2f' % (checknum, amount)
430...
431Check 1200 is for $120.15
432Check 1201 is for $764.05
433Check 1202 is for $823.14
434
435>>> import operator
Guido van Rossum805365e2007-05-07 22:24:25 +0000436>>> for cube in imap(operator.pow, range(1,5), repeat(3)):
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000437... print cube
438...
4391
4408
44127
Raymond Hettingerd7911a32004-05-01 08:31:36 +000044264
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000443
444>>> reportlines = ['EuroPython', 'Roster', '', 'alex', '', 'laura',
Raymond Hettingerd7911a32004-05-01 08:31:36 +0000445 '', 'martin', '', 'walter', '', 'mark']
Raymond Hettinger3567a872003-06-28 05:44:36 +0000446>>> for name in islice(reportlines, 3, None, 2):
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000447... print name.title()
448...
449Alex
450Laura
451Martin
452Walter
Raymond Hettingerd7911a32004-05-01 08:31:36 +0000453Mark
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000454
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000455# Show a dictionary sorted and grouped by value
456>>> from operator import itemgetter
457>>> d = dict(a=1, b=2, c=1, d=2, e=1, f=2, g=3)
Raymond Hettinger64958a12003-12-17 20:43:33 +0000458>>> di = sorted(d.iteritems(), key=itemgetter(1))
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000459>>> for k, g in groupby(di, key=itemgetter(1)):
460... print k, map(itemgetter(0), g)
461...
4621 ['a', 'c', 'e']
4632 ['b', 'd', 'f']
4643 ['g']
465
Raymond Hettinger734fb572004-01-20 20:04:40 +0000466# Find runs of consecutive numbers using groupby. The key to the solution
467# is differencing with a range so that consecutive numbers all appear in
468# same group.
469>>> data = [ 1, 4,5,6, 10, 15,16,17,18, 22, 25,26,27,28]
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000470>>> for k, g in groupby(enumerate(data), lambda t:t[0]-t[1]):
Raymond Hettinger734fb572004-01-20 20:04:40 +0000471... print map(operator.itemgetter(1), g)
472...
473[1]
474[4, 5, 6]
475[10]
476[15, 16, 17, 18]
477[22]
478[25, 26, 27, 28]
Raymond Hettingerd25c1c62003-12-06 16:23:06 +0000479
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000480\end{verbatim}
481
Raymond Hettingerd7911a32004-05-01 08:31:36 +0000482
483\subsection{Recipes \label{itertools-recipes}}
484
485This section shows recipes for creating an extended toolset using the
486existing itertools as building blocks.
487
488The extended tools offer the same high performance as the underlying
489toolset. The superior memory performance is kept by processing elements one
490at a time rather than bringing the whole iterable into memory all at once.
491Code volume is kept small by linking the tools together in a functional style
492which helps eliminate temporary variables. High speed is retained by
493preferring ``vectorized'' building blocks over the use of for-loops and
494generators which incur interpreter overhead.
495
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000496
497\begin{verbatim}
Raymond Hettingera098b332003-09-08 23:58:40 +0000498def take(n, seq):
499 return list(islice(seq, n))
500
Raymond Hettinger9e386412003-08-25 05:06:09 +0000501def enumerate(iterable):
502 return izip(count(), iterable)
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000503
Raymond Hettinger9e386412003-08-25 05:06:09 +0000504def tabulate(function):
505 "Return function(0), function(1), ..."
506 return imap(function, count())
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000507
Raymond Hettinger9e386412003-08-25 05:06:09 +0000508def iteritems(mapping):
509 return izip(mapping.iterkeys(), mapping.itervalues())
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000510
Raymond Hettinger9e386412003-08-25 05:06:09 +0000511def nth(iterable, n):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000512 "Returns the nth item or raise IndexError"
513 return list(islice(iterable, n, n+1))[0]
Raymond Hettinger60eca932003-02-09 06:40:58 +0000514
Raymond Hettingerf77d0332005-03-11 22:17:30 +0000515def all(seq, pred=None):
516 "Returns True if pred(x) is true for every element in the iterable"
Raymond Hettinger4533f1f2004-09-23 07:27:39 +0000517 for elem in ifilterfalse(pred, seq):
518 return False
519 return True
Raymond Hettinger60eca932003-02-09 06:40:58 +0000520
Raymond Hettingerf77d0332005-03-11 22:17:30 +0000521def any(seq, pred=None):
522 "Returns True if pred(x) is true for at least one element in the iterable"
Raymond Hettinger4533f1f2004-09-23 07:27:39 +0000523 for elem in ifilter(pred, seq):
524 return True
525 return False
Raymond Hettinger60eca932003-02-09 06:40:58 +0000526
Raymond Hettingerf77d0332005-03-11 22:17:30 +0000527def no(seq, pred=None):
528 "Returns True if pred(x) is false for every element in the iterable"
Raymond Hettinger4533f1f2004-09-23 07:27:39 +0000529 for elem in ifilter(pred, seq):
530 return False
531 return True
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000532
Raymond Hettingerf77d0332005-03-11 22:17:30 +0000533def quantify(seq, pred=None):
534 "Count how many times the predicate is true in the sequence"
Raymond Hettinger9e386412003-08-25 05:06:09 +0000535 return sum(imap(pred, seq))
Raymond Hettingerc7d77662003-08-08 02:40:28 +0000536
Raymond Hettinger9e386412003-08-25 05:06:09 +0000537def padnone(seq):
Raymond Hettingerd7911a32004-05-01 08:31:36 +0000538 """Returns the sequence elements and then returns None indefinitely.
539
540 Useful for emulating the behavior of the built-in map() function.
Raymond Hettingerd7911a32004-05-01 08:31:36 +0000541 """
Raymond Hettinger9e386412003-08-25 05:06:09 +0000542 return chain(seq, repeat(None))
Raymond Hettinger863983e2003-04-23 00:09:42 +0000543
Raymond Hettinger9e386412003-08-25 05:06:09 +0000544def ncycles(seq, n):
545 "Returns the sequence elements n times"
546 return chain(*repeat(seq, n))
Raymond Hettinger863983e2003-04-23 00:09:42 +0000547
Raymond Hettinger9e386412003-08-25 05:06:09 +0000548def dotproduct(vec1, vec2):
549 return sum(imap(operator.mul, vec1, vec2))
Raymond Hettinger863983e2003-04-23 00:09:42 +0000550
Raymond Hettinger6a5b0272003-10-24 08:45:23 +0000551def flatten(listOfLists):
552 return list(chain(*listOfLists))
553
554def repeatfunc(func, times=None, *args):
Raymond Hettingerd7911a32004-05-01 08:31:36 +0000555 """Repeat calls to func with specified arguments.
556
557 Example: repeatfunc(random.random)
Raymond Hettingerd7911a32004-05-01 08:31:36 +0000558 """
Raymond Hettinger6a5b0272003-10-24 08:45:23 +0000559 if times is None:
560 return starmap(func, repeat(args))
561 else:
562 return starmap(func, repeat(args, times))
563
Raymond Hettingerd591f662003-10-26 15:34:50 +0000564def pairwise(iterable):
565 "s -> (s0,s1), (s1,s2), (s2, s3), ..."
566 a, b = tee(iterable)
Georg Brandla18af4e2007-04-21 15:47:16 +0000567 next(b, None)
Raymond Hettingerad983e72003-11-12 14:32:26 +0000568 return izip(a, b)
Raymond Hettingerbefa37d2003-06-18 19:25:37 +0000569
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000570def grouper(n, iterable, padvalue=None):
571 "grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')"
572 return izip(*[chain(iterable, repeat(padvalue, n-1))]*n)
573
574
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000575\end{verbatim}