1 \section{\module{itertools
} ---
2 Functions creating iterators for efficient looping
}
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
}
11 This module implements a number of iterator building blocks inspired
12 by constructs from the Haskell and SML programming languages. Each
13 has been recast in a form suitable for Python.
15 The module standardizes a core set of fast, memory efficient tools
16 that are useful by themselves or in combination. Standardization helps
17 avoid the readability and reliability problems which arise when many
18 different individuals create their own slightly varying implementations,
19 each with their own quirks and naming conventions.
21 The tools are designed to combine readily with one another. This makes
22 it easy to construct more specialized tools succinctly and efficiently
25 For instance, SML provides a tabulation tool:
\code{tabulate(f)
}
26 which produces a sequence
\code{f(
0), f(
1), ...
}. This toolbox
27 provides
\function{imap()
} and
\function{count()
} which can be combined
28 to form
\code{imap(f, count())
} and produce an equivalent result.
30 Likewise, the functional tools are designed to work well with the
31 high-speed functions provided by the
\refmodule{operator
} module.
33 The module author welcomes suggestions for other basic building blocks
34 to be added to future versions of the module.
36 Whether cast in pure python form or C code, tools that use iterators
37 are more memory efficient (and faster) than their list based counterparts.
38 Adopting the principles of just-in-time manufacturing, they create
39 data when and where needed instead of consuming memory with the
40 computer equivalent of ``inventory''.
42 The performance advantage of iterators becomes more acute as the number
43 of elements increases -- at some point, lists grow large enough to
44 to severely impact memory cache performance and start running slowly.
47 \seetext{The Standard ML Basis Library,
48 \citetitle[http://www.standardml.org/Basis/
]
49 {The Standard ML Basis Library
}.
}
51 \seetext{Haskell, A Purely Functional Language,
52 \citetitle[http://www.haskell.org/definition/
]
53 {Definition of Haskell and the Standard Libraries
}.
}
57 \subsection{Itertool functions
\label{itertools-functions
}}
59 The following module functions all construct and return iterators.
60 Some provide streams of infinite length, so they should only be accessed
61 by functions or loops that truncate the stream.
63 \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:
70 def chain
(*iterables):
77 \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.
81 Also, used in \function{izip()} to add sequence numbers. Equivalent to:
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.
95 \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:
103 for element in iterable:
105 saved.append(element)
109 for element in saved:
113 Note, this is the only member of the toolkit that may require
114 significant auxiliary storage (depending on the length of the
118 \begin{funcdesc}{dropwhile}{predicate, iterable}
119 Make an iterator that drops elements from the iterable as long as
120 the predicate is true; afterwards, returns every element. Note,
121 the iterator does not produce \emph{any} output until the predicate
122 is true, so it may have a lengthy start-up time. Equivalent to:
125 def dropwhile(predicate, iterable):
126 iterable = iter(iterable)
129 if predicate(x): continue # drop when predicate is true
133 yield iterable.next()
137 \begin{funcdesc}{ifilter}{predicate, iterable}
138 Make an iterator that filters elements from iterable returning only
139 those for which the predicate is \code{True}.
140 If \var{predicate} is \code{None}, return the items that are true.
144 def ifilter(predicate, iterable):
145 if predicate is None:
154 \begin{funcdesc}{ifilterfalse}{predicate, iterable}
155 Make an iterator that filters elements from iterable returning only
156 those for which the predicate is \code{False}.
157 If \var{predicate} is \code{None}, return the items that are false.
161 def ifilterfalse(predicate, iterable):
162 if predicate is None:
171 \begin{funcdesc}{imap}{function, *iterables}
172 Make an iterator that computes the function using arguments from
173 each of the iterables. If \var{function} is set to \code{None}, then
174 \function{imap()} returns the arguments as a tuple. Like
175 \function{map()} but stops when the shortest iterable is exhausted
176 instead of filling in \code{None} for shorter iterables. The reason
177 for the difference is that infinite iterator arguments are typically
178 an error for \function{map()} (because the output is fully evaluated)
179 but represent a common and useful way of supplying arguments to
184 def imap(function, *iterables):
185 iterables = map(iter, iterables)
187 args = [i.next() for i in iterables]
191 yield function(*args)
195 \begin{funcdesc}{islice}{iterable, \optional{start,} stop \optional{, step}}
196 Make an iterator that returns selected elements from the iterable.
197 If \var{start} is non-zero, then elements from the iterable are skipped
198 until start is reached. Afterward, elements are returned consecutively
199 unless \var{step} is set higher than one which results in items being
200 skipped. If \var{stop} is \code{None}, then iteration continues until
201 the iterator is exhausted, if at all; otherwise, it stops at the specified
202 position. Unlike regular slicing,
203 \function{islice()} does not support negative values for \var{start},
204 \var{stop}, or \var{step}. Can be used to extract related fields
205 from data where the internal structure has been flattened (for
206 example, a multi-line report may list a name field on every
207 third line). Equivalent to:
210 def islice(iterable, *args):
215 for cnt, element in enumerate(iterable):
218 if stop is not None and cnt >= stop:
225 \begin{funcdesc}{izip}{*iterables}
226 Make an iterator that aggregates elements from each of the iterables.
227 Like \function{zip()} except that it returns an iterator instead of
228 a list. Used for lock-step iteration over several iterables at a
232 def izip(*iterables):
233 iterables = map(iter, iterables)
235 result = [i.next() for i in iterables]
240 \begin{funcdesc}{repeat}{object\optional{, times}}
241 Make an iterator that returns \var{object} over and over again.
242 Runs indefinitely unless the \var{times} argument is specified.
243 Used as argument to \function{imap()} for invariant parameters
244 to the called function. Also used with \function{izip()} to create
245 an invariant part of a tuple record. Equivalent to:
248 def repeat(object, times=None):
253 for i in xrange(times):
258 \begin{funcdesc}{starmap}{function, iterable}
259 Make an iterator that computes the function using arguments tuples
260 obtained from the iterable. Used instead of \function{imap()} when
261 argument parameters are already grouped in tuples from a single iterable
262 (the data has been ``pre-zipped''). The difference between
263 \function{imap()} and \function{starmap()} parallels the distinction
264 between \code{function(a,b)} and \code{function(*c)}.
268 def starmap(function, iterable):
269 iterable = iter(iterable)
271 yield function(*iterable.next())
275 \begin{funcdesc}{takewhile}{predicate, iterable}
276 Make an iterator that returns elements from the iterable as long as
277 the predicate is true. Equivalent to:
280 def takewhile(predicate, iterable):
281 iterable = iter(iterable)
292 \subsection{Examples \label{itertools-example}}
294 The following examples show common uses for each tool and
295 demonstrate ways they can be combined.
299 >>> amounts = [120.15, 764.05, 823.14]
300 >>> for checknum, amount in izip(count(1200), amounts):
301 ... print 'Check %d is for $%.2f' % (checknum, amount)
303 Check 1200 is for $120.15
304 Check 1201 is for $764.05
305 Check 1202 is for $823.14
308 >>> for cube in imap(operator.pow, xrange(1,4), repeat(3)):
315 >>> reportlines = ['EuroPython', 'Roster', '', 'alex', '', 'laura',
316 '', 'martin', '', 'walter', '', 'samuele']
317 >>> for name in islice(reportlines, 3, None, 2):
318 ... print name.title()
328 This section has further examples of how itertools can be combined.
329 Note that \function{enumerate()} and \method{iteritems()} already
330 have highly efficient implementations in Python. They are only
331 included here to illustrate how higher level tools can be created
332 from building blocks.
335 >>> def enumerate(iterable):
336 ... return izip(count(), iterable)
338 >>> def tabulate(function):
339 ... "Return function(0), function(1), ..."
340 ... return imap(function, count())
342 >>> def iteritems(mapping):
343 ... return izip(mapping.iterkeys(), mapping.itervalues())
345 >>> def nth(iterable, n):
346 ... "Returns the nth item"
347 ... return list(islice(iterable, n, n+1))
349 >>> def all(pred, seq):
350 ... "Returns True if pred(x) is True for every element in the iterable"
351 ... return not nth(ifilterfalse(pred, seq), 0)
353 >>> def some(pred, seq):
354 ... "Returns True if pred(x) is True at least one element in the iterable"
355 ... return bool(nth(ifilter(pred, seq), 0))
357 >>> def no(pred, seq):
358 ... "Returns True if pred(x) is False for every element in the iterable"
359 ... return not nth(ifilter(pred, seq), 0)
361 >>> def padnone(seq):
362 ... "Returns the sequence elements and then returns None indefinitely"
363 ... return chain(seq, repeat(None))
365 >>> def ncycles(seq, n):
366 ... "Returns the sequence elements n times"
367 ... return chain(*repeat(seq, n))
369 >>> def dotproduct(vec1, vec2):
370 ... return sum(imap(operator.mul, vec1, vec2))
372 >>> def window(seq, n=2):
373 ... "Returns a sliding window (of width n) over data from the iterable"
374 ... " s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ... "
376 ... result = tuple(islice(it, n))
377 ... if len(result) == n:
380 ... result = result[1:] + (elem,)
383 >>> def take(n, seq):
384 ... return list(islice(seq, n))