Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 1 | \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 | |
| 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. |
| 14 | |
Raymond Hettinger | 60eca93 | 2003-02-09 06:40:58 +0000 | [diff] [blame] | 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. |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 20 | |
Raymond Hettinger | 1b18ba4 | 2003-02-21 01:45:34 +0000 | [diff] [blame] | 21 | The tools are designed to combine readily with one another. This makes |
Raymond Hettinger | 60eca93 | 2003-02-09 06:40:58 +0000 | [diff] [blame] | 22 | it easy to construct more specialized tools succinctly and efficiently |
| 23 | in pure Python. |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 24 | |
Raymond Hettinger | 1b18ba4 | 2003-02-21 01:45:34 +0000 | [diff] [blame] | 25 | For instance, SML provides a tabulation tool: \code{tabulate(f)} |
Raymond Hettinger | 60eca93 | 2003-02-09 06:40:58 +0000 | [diff] [blame] | 26 | which produces a sequence \code{f(0), f(1), ...}. This toolbox |
| 27 | provides \function{imap()} and \function{count()} which can be combined |
Raymond Hettinger | 1b18ba4 | 2003-02-21 01:45:34 +0000 | [diff] [blame] | 28 | to form \code{imap(f, count())} and produce an equivalent result. |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 29 | |
Raymond Hettinger | 863983e | 2003-04-23 00:09:42 +0000 | [diff] [blame] | 30 | Likewise, the functional tools are designed to work well with the |
| 31 | high-speed functions provided by the \refmodule{operator} module. |
| 32 | |
| 33 | The module author welcomes suggestions for other basic building blocks |
| 34 | to be added to future versions of the module. |
| 35 | |
Raymond Hettinger | d7911a3 | 2004-05-01 08:31:36 +0000 | [diff] [blame] | 36 | Whether cast in pure python form or compiled code, tools that use iterators |
Raymond Hettinger | 60eca93 | 2003-02-09 06:40:58 +0000 | [diff] [blame] | 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''. |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 41 | |
Raymond Hettinger | 863983e | 2003-04-23 00:09:42 +0000 | [diff] [blame] | 42 | The performance advantage of iterators becomes more acute as the number |
| 43 | of elements increases -- at some point, lists grow large enough to |
Raymond Hettinger | 7e43110 | 2003-09-22 15:00:55 +0000 | [diff] [blame] | 44 | severely impact memory cache performance and start running slowly. |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 45 | |
| 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 | |
| 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. |
| 62 | |
Raymond Hettinger | 61fe64d | 2003-02-23 04:40:07 +0000 | [diff] [blame] | 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: |
| 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 Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 77 | \begin{funcdesc}{count}{\optional{n}} |
| 78 | Make an iterator that returns consecutive integers starting with \var{n}. |
Raymond Hettinger | ff294fe | 2003-12-07 13:00:25 +0000 | [diff] [blame] | 79 | If not specified \var{n} defaults to zero. |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 80 | Does not currently support python long integers. Often used as an |
| 81 | argument to \function{imap()} to generate consecutive data points. |
Raymond Hettinger | c7d7766 | 2003-08-08 02:40:28 +0000 | [diff] [blame] | 82 | Also, used with \function{izip()} to add sequence numbers. Equivalent to: |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 83 | |
| 84 | \begin{verbatim} |
| 85 | def count(n=0): |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 86 | while True: |
Raymond Hettinger | 1b18ba4 | 2003-02-21 01:45:34 +0000 | [diff] [blame] | 87 | yield n |
| 88 | n += 1 |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 89 | \end{verbatim} |
Raymond Hettinger | 2012f17 | 2003-02-07 05:32:58 +0000 | [diff] [blame] | 90 | |
| 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 Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 94 | \end{funcdesc} |
| 95 | |
Raymond Hettinger | 61fe64d | 2003-02-23 04:40:07 +0000 | [diff] [blame] | 96 | \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 Hettinger | c7d7766 | 2003-08-08 02:40:28 +0000 | [diff] [blame] | 107 | while saved: |
Raymond Hettinger | 61fe64d | 2003-02-23 04:40:07 +0000 | [diff] [blame] | 108 | for element in saved: |
| 109 | yield element |
| 110 | \end{verbatim} |
| 111 | |
Raymond Hettinger | 6a5b027 | 2003-10-24 08:45:23 +0000 | [diff] [blame] | 112 | Note, this member of the toolkit may require significant |
| 113 | auxiliary storage (depending on the length of the iterable). |
Raymond Hettinger | 61fe64d | 2003-02-23 04:40:07 +0000 | [diff] [blame] | 114 | \end{funcdesc} |
| 115 | |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 116 | \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 Hettinger | c7d7766 | 2003-08-08 02:40:28 +0000 | [diff] [blame] | 125 | for x in iterable: |
| 126 | if not predicate(x): |
| 127 | yield x |
| 128 | break |
| 129 | for x in iterable: |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 130 | yield x |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 131 | \end{verbatim} |
| 132 | \end{funcdesc} |
| 133 | |
Raymond Hettinger | d25c1c6 | 2003-12-06 16:23:06 +0000 | [diff] [blame] | 134 | \begin{funcdesc}{groupby}{iterable\optional{, key}} |
| 135 | Make an iterator that returns consecutive keys and groups from the |
Raymond Hettinger | 88e8e34 | 2004-07-11 13:20:11 +0000 | [diff] [blame] | 136 | \var{iterable}. The \var{key} is a function computing a key value for each |
Raymond Hettinger | d25c1c6 | 2003-12-06 16:23:06 +0000 | [diff] [blame] | 137 | element. If not specified or is \code{None}, \var{key} defaults to an |
Andrew M. Kuchling | db7dcff | 2003-12-06 22:29:43 +0000 | [diff] [blame] | 138 | identity function and returns the element unchanged. Generally, the |
Raymond Hettinger | d25c1c6 | 2003-12-06 16:23:06 +0000 | [diff] [blame] | 139 | iterable needs to already be sorted on the same key function. |
| 140 | |
| 141 | The returned group is itself an iterator that shares the underlying |
| 142 | iterable with \function{groupby()}. Because the source is shared, when |
| 143 | the \function{groupby} object is advanced, the previous group is no |
| 144 | longer visible. So, if that data is needed later, it should be stored |
| 145 | as a list: |
| 146 | |
| 147 | \begin{verbatim} |
| 148 | groups = [] |
| 149 | uniquekeys = [] |
| 150 | for k, g in groupby(data, keyfunc): |
| 151 | groups.append(list(g)) # Store group iterator as a list |
| 152 | uniquekeys.append(k) |
| 153 | \end{verbatim} |
| 154 | |
| 155 | \function{groupby()} is equivalent to: |
| 156 | |
| 157 | \begin{verbatim} |
| 158 | class groupby(object): |
| 159 | def __init__(self, iterable, key=None): |
| 160 | if key is None: |
| 161 | key = lambda x: x |
| 162 | self.keyfunc = key |
| 163 | self.it = iter(iterable) |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 164 | self.tgtkey = self.currkey = self.currvalue = [] |
Raymond Hettinger | d25c1c6 | 2003-12-06 16:23:06 +0000 | [diff] [blame] | 165 | def __iter__(self): |
| 166 | return self |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 167 | def __next__(self): |
Raymond Hettinger | d25c1c6 | 2003-12-06 16:23:06 +0000 | [diff] [blame] | 168 | while self.currkey == self.tgtkey: |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 169 | self.currvalue = next(self.it) # Exit on StopIteration |
Raymond Hettinger | d25c1c6 | 2003-12-06 16:23:06 +0000 | [diff] [blame] | 170 | self.currkey = self.keyfunc(self.currvalue) |
| 171 | self.tgtkey = self.currkey |
| 172 | return (self.currkey, self._grouper(self.tgtkey)) |
| 173 | def _grouper(self, tgtkey): |
| 174 | while self.currkey == tgtkey: |
| 175 | yield self.currvalue |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 176 | self.currvalue = next(self.it) # Exit on StopIteration |
Raymond Hettinger | d25c1c6 | 2003-12-06 16:23:06 +0000 | [diff] [blame] | 177 | self.currkey = self.keyfunc(self.currvalue) |
| 178 | \end{verbatim} |
| 179 | \versionadded{2.4} |
| 180 | \end{funcdesc} |
| 181 | |
Raymond Hettinger | 60eca93 | 2003-02-09 06:40:58 +0000 | [diff] [blame] | 182 | \begin{funcdesc}{ifilter}{predicate, iterable} |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 183 | Make an iterator that filters elements from iterable returning only |
Raymond Hettinger | 60eca93 | 2003-02-09 06:40:58 +0000 | [diff] [blame] | 184 | those for which the predicate is \code{True}. |
| 185 | If \var{predicate} is \code{None}, return the items that are true. |
| 186 | Equivalent to: |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 187 | |
| 188 | \begin{verbatim} |
Raymond Hettinger | 60eca93 | 2003-02-09 06:40:58 +0000 | [diff] [blame] | 189 | def ifilter(predicate, iterable): |
| 190 | if predicate is None: |
Guido van Rossum | 0c9a318 | 2003-10-20 17:01:07 +0000 | [diff] [blame] | 191 | predicate = bool |
Raymond Hettinger | 60eca93 | 2003-02-09 06:40:58 +0000 | [diff] [blame] | 192 | for x in iterable: |
| 193 | if predicate(x): |
| 194 | yield x |
| 195 | \end{verbatim} |
| 196 | \end{funcdesc} |
| 197 | |
| 198 | \begin{funcdesc}{ifilterfalse}{predicate, iterable} |
| 199 | Make an iterator that filters elements from iterable returning only |
| 200 | those for which the predicate is \code{False}. |
| 201 | If \var{predicate} is \code{None}, return the items that are false. |
| 202 | Equivalent to: |
| 203 | |
| 204 | \begin{verbatim} |
| 205 | def ifilterfalse(predicate, iterable): |
| 206 | if predicate is None: |
Guido van Rossum | 0c9a318 | 2003-10-20 17:01:07 +0000 | [diff] [blame] | 207 | predicate = bool |
Raymond Hettinger | 60eca93 | 2003-02-09 06:40:58 +0000 | [diff] [blame] | 208 | for x in iterable: |
| 209 | if not predicate(x): |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 210 | yield x |
| 211 | \end{verbatim} |
| 212 | \end{funcdesc} |
| 213 | |
| 214 | \begin{funcdesc}{imap}{function, *iterables} |
| 215 | Make an iterator that computes the function using arguments from |
| 216 | each of the iterables. If \var{function} is set to \code{None}, then |
| 217 | \function{imap()} returns the arguments as a tuple. Like |
| 218 | \function{map()} but stops when the shortest iterable is exhausted |
| 219 | instead of filling in \code{None} for shorter iterables. The reason |
| 220 | for the difference is that infinite iterator arguments are typically |
| 221 | an error for \function{map()} (because the output is fully evaluated) |
| 222 | but represent a common and useful way of supplying arguments to |
| 223 | \function{imap()}. |
| 224 | Equivalent to: |
| 225 | |
| 226 | \begin{verbatim} |
| 227 | def imap(function, *iterables): |
| 228 | iterables = map(iter, iterables) |
| 229 | while True: |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 230 | args = [next(i) for i in iterables] |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 231 | if function is None: |
| 232 | yield tuple(args) |
| 233 | else: |
| 234 | yield function(*args) |
| 235 | \end{verbatim} |
| 236 | \end{funcdesc} |
| 237 | |
| 238 | \begin{funcdesc}{islice}{iterable, \optional{start,} stop \optional{, step}} |
| 239 | Make an iterator that returns selected elements from the iterable. |
| 240 | If \var{start} is non-zero, then elements from the iterable are skipped |
| 241 | until start is reached. Afterward, elements are returned consecutively |
| 242 | unless \var{step} is set higher than one which results in items being |
Raymond Hettinger | 341deb7 | 2003-05-02 19:44:20 +0000 | [diff] [blame] | 243 | skipped. If \var{stop} is \code{None}, then iteration continues until |
| 244 | the iterator is exhausted, if at all; otherwise, it stops at the specified |
| 245 | position. Unlike regular slicing, |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 246 | \function{islice()} does not support negative values for \var{start}, |
| 247 | \var{stop}, or \var{step}. Can be used to extract related fields |
| 248 | from data where the internal structure has been flattened (for |
| 249 | example, a multi-line report may list a name field on every |
| 250 | third line). Equivalent to: |
| 251 | |
| 252 | \begin{verbatim} |
Raymond Hettinger | 1b2e0d9 | 2005-03-27 20:19:05 +0000 | [diff] [blame] | 253 | def islice(iterable, *args): |
Raymond Hettinger | 341deb7 | 2003-05-02 19:44:20 +0000 | [diff] [blame] | 254 | s = slice(*args) |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 255 | it = iter(range(s.start or 0, s.stop or sys.maxint, s.step or 1)) |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 256 | nexti = next(it) |
Raymond Hettinger | fdf3bd6 | 2005-03-27 20:11:44 +0000 | [diff] [blame] | 257 | for i, element in enumerate(iterable): |
| 258 | if i == nexti: |
| 259 | yield element |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 260 | nexti = next(it) |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 261 | \end{verbatim} |
Raymond Hettinger | b259405 | 2004-12-05 09:25:51 +0000 | [diff] [blame] | 262 | |
| 263 | If \var{start} is \code{None}, then iteration starts at zero. |
| 264 | If \var{step} is \code{None}, then the step defaults to one. |
| 265 | \versionchanged[accept \code{None} values for default \var{start} and |
| 266 | \var{step}]{2.5} |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 267 | \end{funcdesc} |
| 268 | |
| 269 | \begin{funcdesc}{izip}{*iterables} |
| 270 | Make an iterator that aggregates elements from each of the iterables. |
| 271 | Like \function{zip()} except that it returns an iterator instead of |
| 272 | a list. Used for lock-step iteration over several iterables at a |
| 273 | time. Equivalent to: |
| 274 | |
| 275 | \begin{verbatim} |
| 276 | def izip(*iterables): |
| 277 | iterables = map(iter, iterables) |
Raymond Hettinger | b5a4208 | 2003-08-08 05:10:41 +0000 | [diff] [blame] | 278 | while iterables: |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 279 | result = [next(it) for it in iterables] |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 280 | yield tuple(result) |
| 281 | \end{verbatim} |
Raymond Hettinger | b5a4208 | 2003-08-08 05:10:41 +0000 | [diff] [blame] | 282 | |
| 283 | \versionchanged[When no iterables are specified, returns a zero length |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 284 | iterator instead of raising a \exception{TypeError} |
| 285 | exception]{2.4} |
| 286 | |
| 287 | Note, the left-to-right evaluation order of the iterables is guaranteed. |
| 288 | This makes possible an idiom for clustering a data series into n-length |
| 289 | groups using \samp{izip(*[iter(s)]*n)}. For data that doesn't fit |
| 290 | n-length groups exactly, the last tuple can be pre-padded with fill |
| 291 | values using \samp{izip(*[chain(s, [None]*(n-1))]*n)}. |
| 292 | |
| 293 | Note, when \function{izip()} is used with unequal length inputs, subsequent |
| 294 | iteration over the longer iterables cannot reliably be continued after |
| 295 | \function{izip()} terminates. Potentially, up to one entry will be missing |
| 296 | from each of the left-over iterables. This occurs because a value is fetched |
| 297 | from each iterator in-turn, but the process ends when one of the iterators |
| 298 | terminates. This leaves the last fetched values in limbo (they cannot be |
| 299 | returned in a final, incomplete tuple and they are cannot be pushed back |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 300 | into the iterator for retrieval with \code{next(it)}). In general, |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 301 | \function{izip()} should only be used with unequal length inputs when you |
| 302 | don't care about trailing, unmatched values from the longer iterables. |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 303 | \end{funcdesc} |
| 304 | |
Thomas Wouters | cf297e4 | 2007-02-23 15:07:44 +0000 | [diff] [blame] | 305 | \begin{funcdesc}{izip_longest}{*iterables\optional{, fillvalue}} |
| 306 | Make an iterator that aggregates elements from each of the iterables. |
| 307 | If the iterables are of uneven length, missing values are filled-in |
| 308 | with \var{fillvalue}. Iteration continues until the longest iterable |
| 309 | is exhausted. Equivalent to: |
| 310 | |
| 311 | \begin{verbatim} |
| 312 | def izip_longest(*args, **kwds): |
| 313 | fillvalue = kwds.get('fillvalue') |
| 314 | def sentinel(counter = ([fillvalue]*(len(args)-1)).pop): |
| 315 | yield counter() # yields the fillvalue, or raises IndexError |
| 316 | fillers = repeat(fillvalue) |
| 317 | iters = [chain(it, sentinel(), fillers) for it in args] |
| 318 | try: |
| 319 | for tup in izip(*iters): |
| 320 | yield tup |
| 321 | except IndexError: |
| 322 | pass |
| 323 | \end{verbatim} |
| 324 | |
| 325 | If one of the iterables is potentially infinite, then the |
| 326 | \function{izip_longest()} function should be wrapped with something |
| 327 | that limits the number of calls (for example \function{islice()} or |
| 328 | \function{take()}). |
| 329 | \versionadded{2.6} |
| 330 | \end{funcdesc} |
| 331 | |
Raymond Hettinger | 61fe64d | 2003-02-23 04:40:07 +0000 | [diff] [blame] | 332 | \begin{funcdesc}{repeat}{object\optional{, times}} |
Raymond Hettinger | 1b18ba4 | 2003-02-21 01:45:34 +0000 | [diff] [blame] | 333 | Make an iterator that returns \var{object} over and over again. |
Raymond Hettinger | 61fe64d | 2003-02-23 04:40:07 +0000 | [diff] [blame] | 334 | Runs indefinitely unless the \var{times} argument is specified. |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 335 | Used as argument to \function{imap()} for invariant parameters |
Raymond Hettinger | 1b18ba4 | 2003-02-21 01:45:34 +0000 | [diff] [blame] | 336 | to the called function. Also used with \function{izip()} to create |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 337 | an invariant part of a tuple record. Equivalent to: |
| 338 | |
| 339 | \begin{verbatim} |
Raymond Hettinger | 61fe64d | 2003-02-23 04:40:07 +0000 | [diff] [blame] | 340 | def repeat(object, times=None): |
| 341 | if times is None: |
| 342 | while True: |
| 343 | yield object |
| 344 | else: |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 345 | for i in range(times): |
Raymond Hettinger | 61fe64d | 2003-02-23 04:40:07 +0000 | [diff] [blame] | 346 | yield object |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 347 | \end{verbatim} |
| 348 | \end{funcdesc} |
| 349 | |
| 350 | \begin{funcdesc}{starmap}{function, iterable} |
| 351 | Make an iterator that computes the function using arguments tuples |
| 352 | obtained from the iterable. Used instead of \function{imap()} when |
| 353 | argument parameters are already grouped in tuples from a single iterable |
| 354 | (the data has been ``pre-zipped''). The difference between |
Raymond Hettinger | 1b18ba4 | 2003-02-21 01:45:34 +0000 | [diff] [blame] | 355 | \function{imap()} and \function{starmap()} parallels the distinction |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 356 | between \code{function(a,b)} and \code{function(*c)}. |
| 357 | Equivalent to: |
| 358 | |
| 359 | \begin{verbatim} |
| 360 | def starmap(function, iterable): |
| 361 | iterable = iter(iterable) |
| 362 | while True: |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 363 | yield function(*next(iterable)) |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 364 | \end{verbatim} |
| 365 | \end{funcdesc} |
| 366 | |
| 367 | \begin{funcdesc}{takewhile}{predicate, iterable} |
| 368 | Make an iterator that returns elements from the iterable as long as |
| 369 | the predicate is true. Equivalent to: |
| 370 | |
| 371 | \begin{verbatim} |
| 372 | def takewhile(predicate, iterable): |
Raymond Hettinger | c7d7766 | 2003-08-08 02:40:28 +0000 | [diff] [blame] | 373 | for x in iterable: |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 374 | if predicate(x): |
| 375 | yield x |
| 376 | else: |
| 377 | break |
| 378 | \end{verbatim} |
| 379 | \end{funcdesc} |
| 380 | |
Raymond Hettinger | ad983e7 | 2003-11-12 14:32:26 +0000 | [diff] [blame] | 381 | \begin{funcdesc}{tee}{iterable\optional{, n=2}} |
| 382 | Return \var{n} independent iterators from a single iterable. |
Raymond Hettinger | 88e8e34 | 2004-07-11 13:20:11 +0000 | [diff] [blame] | 383 | The case where \code{n==2} is equivalent to: |
Raymond Hettinger | 6a5b027 | 2003-10-24 08:45:23 +0000 | [diff] [blame] | 384 | |
| 385 | \begin{verbatim} |
| 386 | def tee(iterable): |
| 387 | def gen(next, data={}, cnt=[0]): |
| 388 | for i in count(): |
| 389 | if i == cnt[0]: |
| 390 | item = data[i] = next() |
| 391 | cnt[0] += 1 |
| 392 | else: |
| 393 | item = data.pop(i) |
| 394 | yield item |
| 395 | it = iter(iterable) |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 396 | return (gen(it.__next__), gen(it.__next__)) |
Raymond Hettinger | 6a5b027 | 2003-10-24 08:45:23 +0000 | [diff] [blame] | 397 | \end{verbatim} |
| 398 | |
Raymond Hettinger | ad983e7 | 2003-11-12 14:32:26 +0000 | [diff] [blame] | 399 | Note, once \function{tee()} has made a split, the original \var{iterable} |
| 400 | should not be used anywhere else; otherwise, the \var{iterable} could get |
| 401 | advanced without the tee objects being informed. |
| 402 | |
Raymond Hettinger | 6a5b027 | 2003-10-24 08:45:23 +0000 | [diff] [blame] | 403 | Note, this member of the toolkit may require significant auxiliary |
| 404 | storage (depending on how much temporary data needs to be stored). |
Andrew M. Kuchling | 3435820 | 2003-12-18 13:28:35 +0000 | [diff] [blame] | 405 | In general, if one iterator is going to use most or all of the data before |
Raymond Hettinger | 6a5b027 | 2003-10-24 08:45:23 +0000 | [diff] [blame] | 406 | the other iterator, it is faster to use \function{list()} instead of |
| 407 | \function{tee()}. |
| 408 | \versionadded{2.4} |
| 409 | \end{funcdesc} |
| 410 | |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 411 | |
| 412 | \subsection{Examples \label{itertools-example}} |
| 413 | |
| 414 | The following examples show common uses for each tool and |
| 415 | demonstrate ways they can be combined. |
| 416 | |
| 417 | \begin{verbatim} |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 418 | |
| 419 | >>> amounts = [120.15, 764.05, 823.14] |
| 420 | >>> for checknum, amount in izip(count(1200), amounts): |
| 421 | ... print 'Check %d is for $%.2f' % (checknum, amount) |
| 422 | ... |
| 423 | Check 1200 is for $120.15 |
| 424 | Check 1201 is for $764.05 |
| 425 | Check 1202 is for $823.14 |
| 426 | |
| 427 | >>> import operator |
Guido van Rossum | 805365e | 2007-05-07 22:24:25 +0000 | [diff] [blame] | 428 | >>> for cube in imap(operator.pow, range(1,5), repeat(3)): |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 429 | ... print cube |
| 430 | ... |
| 431 | 1 |
| 432 | 8 |
| 433 | 27 |
Raymond Hettinger | d7911a3 | 2004-05-01 08:31:36 +0000 | [diff] [blame] | 434 | 64 |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 435 | |
| 436 | >>> reportlines = ['EuroPython', 'Roster', '', 'alex', '', 'laura', |
Raymond Hettinger | d7911a3 | 2004-05-01 08:31:36 +0000 | [diff] [blame] | 437 | '', 'martin', '', 'walter', '', 'mark'] |
Raymond Hettinger | 3567a87 | 2003-06-28 05:44:36 +0000 | [diff] [blame] | 438 | >>> for name in islice(reportlines, 3, None, 2): |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 439 | ... print name.title() |
| 440 | ... |
| 441 | Alex |
| 442 | Laura |
| 443 | Martin |
| 444 | Walter |
Raymond Hettinger | d7911a3 | 2004-05-01 08:31:36 +0000 | [diff] [blame] | 445 | Mark |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 446 | |
Raymond Hettinger | d25c1c6 | 2003-12-06 16:23:06 +0000 | [diff] [blame] | 447 | # Show a dictionary sorted and grouped by value |
| 448 | >>> from operator import itemgetter |
| 449 | >>> d = dict(a=1, b=2, c=1, d=2, e=1, f=2, g=3) |
Raymond Hettinger | 64958a1 | 2003-12-17 20:43:33 +0000 | [diff] [blame] | 450 | >>> di = sorted(d.iteritems(), key=itemgetter(1)) |
Raymond Hettinger | d25c1c6 | 2003-12-06 16:23:06 +0000 | [diff] [blame] | 451 | >>> for k, g in groupby(di, key=itemgetter(1)): |
| 452 | ... print k, map(itemgetter(0), g) |
| 453 | ... |
| 454 | 1 ['a', 'c', 'e'] |
| 455 | 2 ['b', 'd', 'f'] |
| 456 | 3 ['g'] |
| 457 | |
Raymond Hettinger | 734fb57 | 2004-01-20 20:04:40 +0000 | [diff] [blame] | 458 | # Find runs of consecutive numbers using groupby. The key to the solution |
| 459 | # is differencing with a range so that consecutive numbers all appear in |
| 460 | # same group. |
| 461 | >>> data = [ 1, 4,5,6, 10, 15,16,17,18, 22, 25,26,27,28] |
Guido van Rossum | 1bc535d | 2007-05-15 18:46:22 +0000 | [diff] [blame^] | 462 | >>> for k, g in groupby(enumerate(data), lambda t:t[0]-t[1]): |
Raymond Hettinger | 734fb57 | 2004-01-20 20:04:40 +0000 | [diff] [blame] | 463 | ... print map(operator.itemgetter(1), g) |
| 464 | ... |
| 465 | [1] |
| 466 | [4, 5, 6] |
| 467 | [10] |
| 468 | [15, 16, 17, 18] |
| 469 | [22] |
| 470 | [25, 26, 27, 28] |
Raymond Hettinger | d25c1c6 | 2003-12-06 16:23:06 +0000 | [diff] [blame] | 471 | |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 472 | \end{verbatim} |
| 473 | |
Raymond Hettinger | d7911a3 | 2004-05-01 08:31:36 +0000 | [diff] [blame] | 474 | |
| 475 | \subsection{Recipes \label{itertools-recipes}} |
| 476 | |
| 477 | This section shows recipes for creating an extended toolset using the |
| 478 | existing itertools as building blocks. |
| 479 | |
| 480 | The extended tools offer the same high performance as the underlying |
| 481 | toolset. The superior memory performance is kept by processing elements one |
| 482 | at a time rather than bringing the whole iterable into memory all at once. |
| 483 | Code volume is kept small by linking the tools together in a functional style |
| 484 | which helps eliminate temporary variables. High speed is retained by |
| 485 | preferring ``vectorized'' building blocks over the use of for-loops and |
| 486 | generators which incur interpreter overhead. |
| 487 | |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 488 | |
| 489 | \begin{verbatim} |
Raymond Hettinger | a098b33 | 2003-09-08 23:58:40 +0000 | [diff] [blame] | 490 | def take(n, seq): |
| 491 | return list(islice(seq, n)) |
| 492 | |
Raymond Hettinger | 9e38641 | 2003-08-25 05:06:09 +0000 | [diff] [blame] | 493 | def enumerate(iterable): |
| 494 | return izip(count(), iterable) |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 495 | |
Raymond Hettinger | 9e38641 | 2003-08-25 05:06:09 +0000 | [diff] [blame] | 496 | def tabulate(function): |
| 497 | "Return function(0), function(1), ..." |
| 498 | return imap(function, count()) |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 499 | |
Raymond Hettinger | 9e38641 | 2003-08-25 05:06:09 +0000 | [diff] [blame] | 500 | def iteritems(mapping): |
| 501 | return izip(mapping.iterkeys(), mapping.itervalues()) |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 502 | |
Raymond Hettinger | 9e38641 | 2003-08-25 05:06:09 +0000 | [diff] [blame] | 503 | def nth(iterable, n): |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 504 | "Returns the nth item or raise IndexError" |
| 505 | return list(islice(iterable, n, n+1))[0] |
Raymond Hettinger | 60eca93 | 2003-02-09 06:40:58 +0000 | [diff] [blame] | 506 | |
Raymond Hettinger | f77d033 | 2005-03-11 22:17:30 +0000 | [diff] [blame] | 507 | def all(seq, pred=None): |
| 508 | "Returns True if pred(x) is true for every element in the iterable" |
Raymond Hettinger | 4533f1f | 2004-09-23 07:27:39 +0000 | [diff] [blame] | 509 | for elem in ifilterfalse(pred, seq): |
| 510 | return False |
| 511 | return True |
Raymond Hettinger | 60eca93 | 2003-02-09 06:40:58 +0000 | [diff] [blame] | 512 | |
Raymond Hettinger | f77d033 | 2005-03-11 22:17:30 +0000 | [diff] [blame] | 513 | def any(seq, pred=None): |
| 514 | "Returns True if pred(x) is true for at least one element in the iterable" |
Raymond Hettinger | 4533f1f | 2004-09-23 07:27:39 +0000 | [diff] [blame] | 515 | for elem in ifilter(pred, seq): |
| 516 | return True |
| 517 | return False |
Raymond Hettinger | 60eca93 | 2003-02-09 06:40:58 +0000 | [diff] [blame] | 518 | |
Raymond Hettinger | f77d033 | 2005-03-11 22:17:30 +0000 | [diff] [blame] | 519 | def no(seq, pred=None): |
| 520 | "Returns True if pred(x) is false for every element in the iterable" |
Raymond Hettinger | 4533f1f | 2004-09-23 07:27:39 +0000 | [diff] [blame] | 521 | for elem in ifilter(pred, seq): |
| 522 | return False |
| 523 | return True |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 524 | |
Raymond Hettinger | f77d033 | 2005-03-11 22:17:30 +0000 | [diff] [blame] | 525 | def quantify(seq, pred=None): |
| 526 | "Count how many times the predicate is true in the sequence" |
Raymond Hettinger | 9e38641 | 2003-08-25 05:06:09 +0000 | [diff] [blame] | 527 | return sum(imap(pred, seq)) |
Raymond Hettinger | c7d7766 | 2003-08-08 02:40:28 +0000 | [diff] [blame] | 528 | |
Raymond Hettinger | 9e38641 | 2003-08-25 05:06:09 +0000 | [diff] [blame] | 529 | def padnone(seq): |
Raymond Hettinger | d7911a3 | 2004-05-01 08:31:36 +0000 | [diff] [blame] | 530 | """Returns the sequence elements and then returns None indefinitely. |
| 531 | |
| 532 | Useful for emulating the behavior of the built-in map() function. |
Raymond Hettinger | d7911a3 | 2004-05-01 08:31:36 +0000 | [diff] [blame] | 533 | """ |
Raymond Hettinger | 9e38641 | 2003-08-25 05:06:09 +0000 | [diff] [blame] | 534 | return chain(seq, repeat(None)) |
Raymond Hettinger | 863983e | 2003-04-23 00:09:42 +0000 | [diff] [blame] | 535 | |
Raymond Hettinger | 9e38641 | 2003-08-25 05:06:09 +0000 | [diff] [blame] | 536 | def ncycles(seq, n): |
| 537 | "Returns the sequence elements n times" |
| 538 | return chain(*repeat(seq, n)) |
Raymond Hettinger | 863983e | 2003-04-23 00:09:42 +0000 | [diff] [blame] | 539 | |
Raymond Hettinger | 9e38641 | 2003-08-25 05:06:09 +0000 | [diff] [blame] | 540 | def dotproduct(vec1, vec2): |
| 541 | return sum(imap(operator.mul, vec1, vec2)) |
Raymond Hettinger | 863983e | 2003-04-23 00:09:42 +0000 | [diff] [blame] | 542 | |
Raymond Hettinger | 6a5b027 | 2003-10-24 08:45:23 +0000 | [diff] [blame] | 543 | def flatten(listOfLists): |
| 544 | return list(chain(*listOfLists)) |
| 545 | |
| 546 | def repeatfunc(func, times=None, *args): |
Raymond Hettinger | d7911a3 | 2004-05-01 08:31:36 +0000 | [diff] [blame] | 547 | """Repeat calls to func with specified arguments. |
| 548 | |
| 549 | Example: repeatfunc(random.random) |
Raymond Hettinger | d7911a3 | 2004-05-01 08:31:36 +0000 | [diff] [blame] | 550 | """ |
Raymond Hettinger | 6a5b027 | 2003-10-24 08:45:23 +0000 | [diff] [blame] | 551 | if times is None: |
| 552 | return starmap(func, repeat(args)) |
| 553 | else: |
| 554 | return starmap(func, repeat(args, times)) |
| 555 | |
Raymond Hettinger | d591f66 | 2003-10-26 15:34:50 +0000 | [diff] [blame] | 556 | def pairwise(iterable): |
| 557 | "s -> (s0,s1), (s1,s2), (s2, s3), ..." |
| 558 | a, b = tee(iterable) |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 559 | next(b, None) |
Raymond Hettinger | ad983e7 | 2003-11-12 14:32:26 +0000 | [diff] [blame] | 560 | return izip(a, b) |
Raymond Hettinger | befa37d | 2003-06-18 19:25:37 +0000 | [diff] [blame] | 561 | |
Thomas Wouters | 49fd7fa | 2006-04-21 10:40:58 +0000 | [diff] [blame] | 562 | def grouper(n, iterable, padvalue=None): |
| 563 | "grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')" |
| 564 | return izip(*[chain(iterable, repeat(padvalue, n-1))]*n) |
| 565 | |
| 566 | |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 567 | \end{verbatim} |