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 | 60eca93 | 2003-02-09 06:40:58 +0000 | [diff] [blame] | 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''. |
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 |
| 44 | to 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}. |
| 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: |
| 82 | |
| 83 | \begin{verbatim} |
| 84 | def count(n=0): |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 85 | while True: |
Raymond Hettinger | 1b18ba4 | 2003-02-21 01:45:34 +0000 | [diff] [blame] | 86 | yield n |
| 87 | n += 1 |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 88 | \end{verbatim} |
Raymond Hettinger | 2012f17 | 2003-02-07 05:32:58 +0000 | [diff] [blame] | 89 | |
| 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 Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 93 | \end{funcdesc} |
| 94 | |
Raymond Hettinger | 61fe64d | 2003-02-23 04:40:07 +0000 | [diff] [blame] | 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: |
| 99 | |
| 100 | \begin{verbatim} |
| 101 | def cycle(iterable): |
| 102 | saved = [] |
| 103 | for element in iterable: |
| 104 | yield element |
| 105 | saved.append(element) |
| 106 | if len(saved) == 0: |
| 107 | return |
| 108 | while True: |
| 109 | for element in saved: |
| 110 | yield element |
| 111 | \end{verbatim} |
| 112 | |
| 113 | Note, this is the only member of the toolkit that may require |
| 114 | significant auxiliary storage (depending on the length of the |
Raymond Hettinger | 863983e | 2003-04-23 00:09:42 +0000 | [diff] [blame] | 115 | iterable). |
Raymond Hettinger | 61fe64d | 2003-02-23 04:40:07 +0000 | [diff] [blame] | 116 | \end{funcdesc} |
| 117 | |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 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: |
| 123 | |
| 124 | \begin{verbatim} |
| 125 | def dropwhile(predicate, iterable): |
| 126 | iterable = iter(iterable) |
| 127 | while True: |
| 128 | x = iterable.next() |
| 129 | if predicate(x): continue # drop when predicate is true |
| 130 | yield x |
| 131 | break |
| 132 | while True: |
| 133 | yield iterable.next() |
| 134 | \end{verbatim} |
| 135 | \end{funcdesc} |
| 136 | |
Raymond Hettinger | 60eca93 | 2003-02-09 06:40:58 +0000 | [diff] [blame] | 137 | \begin{funcdesc}{ifilter}{predicate, iterable} |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 138 | Make an iterator that filters elements from iterable returning only |
Raymond Hettinger | 60eca93 | 2003-02-09 06:40:58 +0000 | [diff] [blame] | 139 | those for which the predicate is \code{True}. |
| 140 | If \var{predicate} is \code{None}, return the items that are true. |
| 141 | Equivalent to: |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 142 | |
| 143 | \begin{verbatim} |
Raymond Hettinger | 60eca93 | 2003-02-09 06:40:58 +0000 | [diff] [blame] | 144 | def ifilter(predicate, iterable): |
| 145 | if predicate is None: |
| 146 | def predicate(x): |
| 147 | return x |
| 148 | for x in iterable: |
| 149 | if predicate(x): |
| 150 | yield x |
| 151 | \end{verbatim} |
| 152 | \end{funcdesc} |
| 153 | |
| 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. |
| 158 | Equivalent to: |
| 159 | |
| 160 | \begin{verbatim} |
| 161 | def ifilterfalse(predicate, iterable): |
| 162 | if predicate is None: |
| 163 | def predicate(x): |
| 164 | return x |
| 165 | for x in iterable: |
| 166 | if not predicate(x): |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 167 | yield x |
| 168 | \end{verbatim} |
| 169 | \end{funcdesc} |
| 170 | |
| 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 |
| 180 | \function{imap()}. |
| 181 | Equivalent to: |
| 182 | |
| 183 | \begin{verbatim} |
| 184 | def imap(function, *iterables): |
| 185 | iterables = map(iter, iterables) |
| 186 | while True: |
| 187 | args = [i.next() for i in iterables] |
| 188 | if function is None: |
| 189 | yield tuple(args) |
| 190 | else: |
| 191 | yield function(*args) |
| 192 | \end{verbatim} |
| 193 | \end{funcdesc} |
| 194 | |
| 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 |
Raymond Hettinger | 14ef54c | 2003-05-02 19:04:37 +0000 | [diff] [blame^] | 200 | skipped. If \var{stop} is not specified or is \code{None}, then iteration |
| 201 | continues indefinitely; otherwise, it stops at the specified position. |
| 202 | Unlike regular slicing, |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 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: |
| 208 | |
| 209 | \begin{verbatim} |
| 210 | def islice(iterable, *args): |
Raymond Hettinger | 14ef54c | 2003-05-02 19:04:37 +0000 | [diff] [blame^] | 211 | if args: |
| 212 | s = slice(*args) |
| 213 | next = s.start or 0 |
| 214 | stop = s.stop |
| 215 | step = s.step or 1 |
| 216 | else: |
| 217 | next, stop, step = 0, None, 1 |
Raymond Hettinger | 60eca93 | 2003-02-09 06:40:58 +0000 | [diff] [blame] | 218 | for cnt, element in enumerate(iterable): |
| 219 | if cnt < next: |
| 220 | continue |
Raymond Hettinger | 14ef54c | 2003-05-02 19:04:37 +0000 | [diff] [blame^] | 221 | if stop is not None and cnt >= stop: |
Raymond Hettinger | 60eca93 | 2003-02-09 06:40:58 +0000 | [diff] [blame] | 222 | break |
| 223 | yield element |
Raymond Hettinger | 14ef54c | 2003-05-02 19:04:37 +0000 | [diff] [blame^] | 224 | next += step |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 225 | \end{verbatim} |
| 226 | \end{funcdesc} |
| 227 | |
| 228 | \begin{funcdesc}{izip}{*iterables} |
| 229 | Make an iterator that aggregates elements from each of the iterables. |
| 230 | Like \function{zip()} except that it returns an iterator instead of |
| 231 | a list. Used for lock-step iteration over several iterables at a |
| 232 | time. Equivalent to: |
| 233 | |
| 234 | \begin{verbatim} |
| 235 | def izip(*iterables): |
| 236 | iterables = map(iter, iterables) |
| 237 | while True: |
| 238 | result = [i.next() for i in iterables] |
| 239 | yield tuple(result) |
| 240 | \end{verbatim} |
| 241 | \end{funcdesc} |
| 242 | |
Raymond Hettinger | 61fe64d | 2003-02-23 04:40:07 +0000 | [diff] [blame] | 243 | \begin{funcdesc}{repeat}{object\optional{, times}} |
Raymond Hettinger | 1b18ba4 | 2003-02-21 01:45:34 +0000 | [diff] [blame] | 244 | Make an iterator that returns \var{object} over and over again. |
Raymond Hettinger | 61fe64d | 2003-02-23 04:40:07 +0000 | [diff] [blame] | 245 | Runs indefinitely unless the \var{times} argument is specified. |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 246 | Used as argument to \function{imap()} for invariant parameters |
Raymond Hettinger | 1b18ba4 | 2003-02-21 01:45:34 +0000 | [diff] [blame] | 247 | to the called function. Also used with \function{izip()} to create |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 248 | an invariant part of a tuple record. Equivalent to: |
| 249 | |
| 250 | \begin{verbatim} |
Raymond Hettinger | 61fe64d | 2003-02-23 04:40:07 +0000 | [diff] [blame] | 251 | def repeat(object, times=None): |
| 252 | if times is None: |
| 253 | while True: |
| 254 | yield object |
| 255 | else: |
| 256 | for i in xrange(times): |
| 257 | yield object |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 258 | \end{verbatim} |
| 259 | \end{funcdesc} |
| 260 | |
| 261 | \begin{funcdesc}{starmap}{function, iterable} |
| 262 | Make an iterator that computes the function using arguments tuples |
| 263 | obtained from the iterable. Used instead of \function{imap()} when |
| 264 | argument parameters are already grouped in tuples from a single iterable |
| 265 | (the data has been ``pre-zipped''). The difference between |
Raymond Hettinger | 1b18ba4 | 2003-02-21 01:45:34 +0000 | [diff] [blame] | 266 | \function{imap()} and \function{starmap()} parallels the distinction |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 267 | between \code{function(a,b)} and \code{function(*c)}. |
| 268 | Equivalent to: |
| 269 | |
| 270 | \begin{verbatim} |
| 271 | def starmap(function, iterable): |
| 272 | iterable = iter(iterable) |
| 273 | while True: |
| 274 | yield function(*iterable.next()) |
| 275 | \end{verbatim} |
| 276 | \end{funcdesc} |
| 277 | |
| 278 | \begin{funcdesc}{takewhile}{predicate, iterable} |
| 279 | Make an iterator that returns elements from the iterable as long as |
| 280 | the predicate is true. Equivalent to: |
| 281 | |
| 282 | \begin{verbatim} |
| 283 | def takewhile(predicate, iterable): |
| 284 | iterable = iter(iterable) |
| 285 | while True: |
| 286 | x = iterable.next() |
| 287 | if predicate(x): |
| 288 | yield x |
| 289 | else: |
| 290 | break |
| 291 | \end{verbatim} |
| 292 | \end{funcdesc} |
| 293 | |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 294 | |
| 295 | \subsection{Examples \label{itertools-example}} |
| 296 | |
| 297 | The following examples show common uses for each tool and |
| 298 | demonstrate ways they can be combined. |
| 299 | |
| 300 | \begin{verbatim} |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 301 | |
| 302 | >>> amounts = [120.15, 764.05, 823.14] |
| 303 | >>> for checknum, amount in izip(count(1200), amounts): |
| 304 | ... print 'Check %d is for $%.2f' % (checknum, amount) |
| 305 | ... |
| 306 | Check 1200 is for $120.15 |
| 307 | Check 1201 is for $764.05 |
| 308 | Check 1202 is for $823.14 |
| 309 | |
| 310 | >>> import operator |
| 311 | >>> for cube in imap(operator.pow, xrange(1,4), repeat(3)): |
| 312 | ... print cube |
| 313 | ... |
| 314 | 1 |
| 315 | 8 |
| 316 | 27 |
| 317 | |
| 318 | >>> reportlines = ['EuroPython', 'Roster', '', 'alex', '', 'laura', |
| 319 | '', 'martin', '', 'walter', '', 'samuele'] |
| 320 | >>> for name in islice(reportlines, 3, len(reportlines), 2): |
| 321 | ... print name.title() |
| 322 | ... |
| 323 | Alex |
| 324 | Laura |
| 325 | Martin |
| 326 | Walter |
| 327 | Samuele |
| 328 | |
| 329 | \end{verbatim} |
| 330 | |
| 331 | This section has further examples of how itertools can be combined. |
| 332 | Note that \function{enumerate()} and \method{iteritems()} already |
| 333 | have highly efficient implementations in Python. They are only |
| 334 | included here to illustrate how higher level tools can be created |
| 335 | from building blocks. |
| 336 | |
| 337 | \begin{verbatim} |
| 338 | >>> def enumerate(iterable): |
| 339 | ... return izip(count(), iterable) |
| 340 | |
| 341 | >>> def tabulate(function): |
| 342 | ... "Return function(0), function(1), ..." |
| 343 | ... return imap(function, count()) |
| 344 | |
| 345 | >>> def iteritems(mapping): |
| 346 | ... return izip(mapping.iterkeys(), mapping.itervalues()) |
| 347 | |
| 348 | >>> def nth(iterable, n): |
| 349 | ... "Returns the nth item" |
Raymond Hettinger | 60eca93 | 2003-02-09 06:40:58 +0000 | [diff] [blame] | 350 | ... return list(islice(iterable, n, n+1)) |
| 351 | |
| 352 | >>> def all(pred, seq): |
| 353 | ... "Returns True if pred(x) is True for every element in the iterable" |
| 354 | ... return not nth(ifilterfalse(pred, seq), 0) |
| 355 | |
| 356 | >>> def some(pred, seq): |
| 357 | ... "Returns True if pred(x) is True at least one element in the iterable" |
| 358 | ... return bool(nth(ifilter(pred, seq), 0)) |
| 359 | |
| 360 | >>> def no(pred, seq): |
| 361 | ... "Returns True if pred(x) is False for every element in the iterable" |
| 362 | ... return not nth(ifilter(pred, seq), 0) |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 363 | |
Raymond Hettinger | 61fe64d | 2003-02-23 04:40:07 +0000 | [diff] [blame] | 364 | >>> def pairwise(seq): |
| 365 | ... "s -> (s0,s1), (s1,s2), (s2, s3), ..." |
Raymond Hettinger | 14ef54c | 2003-05-02 19:04:37 +0000 | [diff] [blame^] | 366 | ... return izip(seq, islice(seq,1,None)) |
Raymond Hettinger | 61fe64d | 2003-02-23 04:40:07 +0000 | [diff] [blame] | 367 | |
Raymond Hettinger | 863983e | 2003-04-23 00:09:42 +0000 | [diff] [blame] | 368 | >>> def padnone(seq): |
| 369 | ... "Returns the sequence elements and then returns None indefinitely" |
| 370 | ... return chain(seq, repeat(None)) |
| 371 | |
| 372 | >>> def ncycles(seq, n): |
| 373 | ... "Returns the sequence elements n times" |
| 374 | ... return chain(*repeat(seq, n)) |
| 375 | |
| 376 | >>> def dotproduct(vec1, vec2): |
| 377 | ... return sum(imap(operator.mul, vec1, vec2)) |
| 378 | |
Raymond Hettinger | 96ef811 | 2003-02-01 00:10:11 +0000 | [diff] [blame] | 379 | \end{verbatim} |