blob: 453d16e4d7b89726303a28506f1044dc2edb52db [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 Hettinger60eca932003-02-09 06:40:58 +000036Whether cast in pure python form or C code, tools that use iterators
37are 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
44to severely 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}.
79 Does not currently support python long integers. Often used as an
80 argument to \function{imap()} to generate consecutive data points.
Raymond Hettingerc7d77662003-08-08 02:40:28 +000081 Also, used with \function{izip()} to add sequence numbers. Equivalent to:
Raymond Hettinger96ef8112003-02-01 00:10:11 +000082
83 \begin{verbatim}
84 def count(n=0):
Raymond Hettinger96ef8112003-02-01 00:10:11 +000085 while True:
Raymond Hettinger1b18ba42003-02-21 01:45:34 +000086 yield n
87 n += 1
Raymond Hettinger96ef8112003-02-01 00:10:11 +000088 \end{verbatim}
Raymond Hettinger2012f172003-02-07 05:32:58 +000089
90 Note, \function{count()} does not check for overflow and will return
91 negative numbers after exceeding \code{sys.maxint}. This behavior
92 may change in the future.
Raymond Hettinger96ef8112003-02-01 00:10:11 +000093\end{funcdesc}
94
Raymond Hettinger61fe64d2003-02-23 04:40:07 +000095\begin{funcdesc}{cycle}{iterable}
96 Make an iterator returning elements from the iterable and saving a
97 copy of each. When the iterable is exhausted, return elements from
98 the saved copy. Repeats indefinitely. Equivalent to:
99
100 \begin{verbatim}
101 def cycle(iterable):
102 saved = []
103 for element in iterable:
104 yield element
105 saved.append(element)
Raymond Hettingerc7d77662003-08-08 02:40:28 +0000106 while saved:
Raymond Hettinger61fe64d2003-02-23 04:40:07 +0000107 for element in saved:
108 yield element
109 \end{verbatim}
110
111 Note, this is the only member of the toolkit that may require
112 significant auxiliary storage (depending on the length of the
Raymond Hettinger863983e2003-04-23 00:09:42 +0000113 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 Hettinger60eca932003-02-09 06:40:58 +0000134\begin{funcdesc}{ifilter}{predicate, iterable}
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000135 Make an iterator that filters elements from iterable returning only
Raymond Hettinger60eca932003-02-09 06:40:58 +0000136 those for which the predicate is \code{True}.
137 If \var{predicate} is \code{None}, return the items that are true.
138 Equivalent to:
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000139
140 \begin{verbatim}
Raymond Hettinger60eca932003-02-09 06:40:58 +0000141 def ifilter(predicate, iterable):
142 if predicate is None:
143 def predicate(x):
144 return x
145 for x in iterable:
146 if predicate(x):
147 yield x
148 \end{verbatim}
149\end{funcdesc}
150
151\begin{funcdesc}{ifilterfalse}{predicate, iterable}
152 Make an iterator that filters elements from iterable returning only
153 those for which the predicate is \code{False}.
154 If \var{predicate} is \code{None}, return the items that are false.
155 Equivalent to:
156
157 \begin{verbatim}
158 def ifilterfalse(predicate, iterable):
159 if predicate is None:
160 def predicate(x):
161 return x
162 for x in iterable:
163 if not predicate(x):
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000164 yield x
165 \end{verbatim}
166\end{funcdesc}
167
168\begin{funcdesc}{imap}{function, *iterables}
169 Make an iterator that computes the function using arguments from
170 each of the iterables. If \var{function} is set to \code{None}, then
171 \function{imap()} returns the arguments as a tuple. Like
172 \function{map()} but stops when the shortest iterable is exhausted
173 instead of filling in \code{None} for shorter iterables. The reason
174 for the difference is that infinite iterator arguments are typically
175 an error for \function{map()} (because the output is fully evaluated)
176 but represent a common and useful way of supplying arguments to
177 \function{imap()}.
178 Equivalent to:
179
180 \begin{verbatim}
181 def imap(function, *iterables):
182 iterables = map(iter, iterables)
183 while True:
184 args = [i.next() for i in iterables]
185 if function is None:
186 yield tuple(args)
187 else:
188 yield function(*args)
189 \end{verbatim}
190\end{funcdesc}
191
192\begin{funcdesc}{islice}{iterable, \optional{start,} stop \optional{, step}}
193 Make an iterator that returns selected elements from the iterable.
194 If \var{start} is non-zero, then elements from the iterable are skipped
195 until start is reached. Afterward, elements are returned consecutively
196 unless \var{step} is set higher than one which results in items being
Raymond Hettinger341deb72003-05-02 19:44:20 +0000197 skipped. If \var{stop} is \code{None}, then iteration continues until
198 the iterator is exhausted, if at all; otherwise, it stops at the specified
199 position. Unlike regular slicing,
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000200 \function{islice()} does not support negative values for \var{start},
201 \var{stop}, or \var{step}. Can be used to extract related fields
202 from data where the internal structure has been flattened (for
203 example, a multi-line report may list a name field on every
204 third line). Equivalent to:
205
206 \begin{verbatim}
207 def islice(iterable, *args):
Raymond Hettinger341deb72003-05-02 19:44:20 +0000208 s = slice(*args)
Raymond Hettingerc7d77662003-08-08 02:40:28 +0000209 next, stop, step = s.start or 0, s.stop, s.step or 1
Raymond Hettinger60eca932003-02-09 06:40:58 +0000210 for cnt, element in enumerate(iterable):
211 if cnt < next:
212 continue
Raymond Hettinger14ef54c2003-05-02 19:04:37 +0000213 if stop is not None and cnt >= stop:
Raymond Hettinger60eca932003-02-09 06:40:58 +0000214 break
215 yield element
Raymond Hettinger14ef54c2003-05-02 19:04:37 +0000216 next += step
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000217 \end{verbatim}
218\end{funcdesc}
219
220\begin{funcdesc}{izip}{*iterables}
221 Make an iterator that aggregates elements from each of the iterables.
222 Like \function{zip()} except that it returns an iterator instead of
223 a list. Used for lock-step iteration over several iterables at a
224 time. Equivalent to:
225
226 \begin{verbatim}
227 def izip(*iterables):
228 iterables = map(iter, iterables)
Raymond Hettingerb5a42082003-08-08 05:10:41 +0000229 while iterables:
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000230 result = [i.next() for i in iterables]
231 yield tuple(result)
232 \end{verbatim}
Raymond Hettingerb5a42082003-08-08 05:10:41 +0000233
234 \versionchanged[When no iterables are specified, returns a zero length
235 iterator instead of raising a TypeError exception]{2.4}
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000236\end{funcdesc}
237
Raymond Hettinger61fe64d2003-02-23 04:40:07 +0000238\begin{funcdesc}{repeat}{object\optional{, times}}
Raymond Hettinger1b18ba42003-02-21 01:45:34 +0000239 Make an iterator that returns \var{object} over and over again.
Raymond Hettinger61fe64d2003-02-23 04:40:07 +0000240 Runs indefinitely unless the \var{times} argument is specified.
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000241 Used as argument to \function{imap()} for invariant parameters
Raymond Hettinger1b18ba42003-02-21 01:45:34 +0000242 to the called function. Also used with \function{izip()} to create
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000243 an invariant part of a tuple record. Equivalent to:
244
245 \begin{verbatim}
Raymond Hettinger61fe64d2003-02-23 04:40:07 +0000246 def repeat(object, times=None):
247 if times is None:
248 while True:
249 yield object
250 else:
251 for i in xrange(times):
252 yield object
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000253 \end{verbatim}
254\end{funcdesc}
255
256\begin{funcdesc}{starmap}{function, iterable}
257 Make an iterator that computes the function using arguments tuples
258 obtained from the iterable. Used instead of \function{imap()} when
259 argument parameters are already grouped in tuples from a single iterable
260 (the data has been ``pre-zipped''). The difference between
Raymond Hettinger1b18ba42003-02-21 01:45:34 +0000261 \function{imap()} and \function{starmap()} parallels the distinction
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000262 between \code{function(a,b)} and \code{function(*c)}.
263 Equivalent to:
264
265 \begin{verbatim}
266 def starmap(function, iterable):
267 iterable = iter(iterable)
268 while True:
269 yield function(*iterable.next())
270 \end{verbatim}
271\end{funcdesc}
272
273\begin{funcdesc}{takewhile}{predicate, iterable}
274 Make an iterator that returns elements from the iterable as long as
275 the predicate is true. Equivalent to:
276
277 \begin{verbatim}
278 def takewhile(predicate, iterable):
Raymond Hettingerc7d77662003-08-08 02:40:28 +0000279 for x in iterable:
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000280 if predicate(x):
281 yield x
282 else:
283 break
284 \end{verbatim}
285\end{funcdesc}
286
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000287
288\subsection{Examples \label{itertools-example}}
289
290The following examples show common uses for each tool and
291demonstrate ways they can be combined.
292
293\begin{verbatim}
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000294
295>>> amounts = [120.15, 764.05, 823.14]
296>>> for checknum, amount in izip(count(1200), amounts):
297... print 'Check %d is for $%.2f' % (checknum, amount)
298...
299Check 1200 is for $120.15
300Check 1201 is for $764.05
301Check 1202 is for $823.14
302
303>>> import operator
304>>> for cube in imap(operator.pow, xrange(1,4), repeat(3)):
305... print cube
306...
3071
3088
30927
310
311>>> reportlines = ['EuroPython', 'Roster', '', 'alex', '', 'laura',
312 '', 'martin', '', 'walter', '', 'samuele']
Raymond Hettinger3567a872003-06-28 05:44:36 +0000313>>> for name in islice(reportlines, 3, None, 2):
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000314... print name.title()
315...
316Alex
317Laura
318Martin
319Walter
320Samuele
321
322\end{verbatim}
323
Raymond Hettingera098b332003-09-08 23:58:40 +0000324This section shows how itertools can be combined to create other more
325powerful itertools. Note that \function{enumerate()} and \method{iteritems()}
326already have efficient implementations in Python. They are only included here
327to illustrate how higher level tools can be created from building blocks.
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000328
329\begin{verbatim}
Raymond Hettingera098b332003-09-08 23:58:40 +0000330def take(n, seq):
331 return list(islice(seq, n))
332
Raymond Hettinger9e386412003-08-25 05:06:09 +0000333def enumerate(iterable):
334 return izip(count(), iterable)
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000335
Raymond Hettinger9e386412003-08-25 05:06:09 +0000336def tabulate(function):
337 "Return function(0), function(1), ..."
338 return imap(function, count())
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000339
Raymond Hettinger9e386412003-08-25 05:06:09 +0000340def iteritems(mapping):
341 return izip(mapping.iterkeys(), mapping.itervalues())
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000342
Raymond Hettinger9e386412003-08-25 05:06:09 +0000343def nth(iterable, n):
344 "Returns the nth item"
345 return list(islice(iterable, n, n+1))
Raymond Hettinger60eca932003-02-09 06:40:58 +0000346
Raymond Hettinger9e386412003-08-25 05:06:09 +0000347def all(pred, seq):
348 "Returns True if pred(x) is True for every element in the iterable"
349 return False not in imap(pred, seq)
Raymond Hettinger60eca932003-02-09 06:40:58 +0000350
Raymond Hettinger9e386412003-08-25 05:06:09 +0000351def some(pred, seq):
352 "Returns True if pred(x) is True at least one element in the iterable"
353 return True in imap(pred, seq)
Raymond Hettinger60eca932003-02-09 06:40:58 +0000354
Raymond Hettinger9e386412003-08-25 05:06:09 +0000355def no(pred, seq):
356 "Returns True if pred(x) is False for every element in the iterable"
357 return True not in imap(pred, seq)
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000358
Raymond Hettinger9e386412003-08-25 05:06:09 +0000359def quantify(pred, seq):
360 "Count how many times the predicate is True in the sequence"
361 return sum(imap(pred, seq))
Raymond Hettingerc7d77662003-08-08 02:40:28 +0000362
Raymond Hettinger9e386412003-08-25 05:06:09 +0000363def padnone(seq):
364 "Returns the sequence elements and then returns None indefinitely"
365 return chain(seq, repeat(None))
Raymond Hettinger863983e2003-04-23 00:09:42 +0000366
Raymond Hettinger9e386412003-08-25 05:06:09 +0000367def ncycles(seq, n):
368 "Returns the sequence elements n times"
369 return chain(*repeat(seq, n))
Raymond Hettinger863983e2003-04-23 00:09:42 +0000370
Raymond Hettinger9e386412003-08-25 05:06:09 +0000371def dotproduct(vec1, vec2):
372 return sum(imap(operator.mul, vec1, vec2))
Raymond Hettinger863983e2003-04-23 00:09:42 +0000373
Raymond Hettinger9e386412003-08-25 05:06:09 +0000374def window(seq, n=2):
375 "Returns a sliding window (of width n) over data from the iterable"
376 " s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ... "
377 it = iter(seq)
378 result = tuple(islice(it, n))
379 if len(result) == n:
380 yield result
381 for elem in it:
382 result = result[1:] + (elem,)
383 yield result
Raymond Hettingerbefa37d2003-06-18 19:25:37 +0000384
Raymond Hettingera098b332003-09-08 23:58:40 +0000385def tee(iterable):
386 "Return two independent iterators from a single iterable"
387 def gen(next, data={}, cnt=[0]):
388 dpop = data.pop
389 for i in count():
390 if i == cnt[0]:
391 item = data[i] = next()
392 cnt[0] += 1
393 else:
394 item = dpop(i)
395 yield item
396 next = iter(iterable).next
397 return (gen(next), gen(next))
Raymond Hettinger3567a872003-06-28 05:44:36 +0000398
Raymond Hettinger96ef8112003-02-01 00:10:11 +0000399\end{verbatim}