Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 1 | |
| 2 | :mod:`itertools` --- Functions creating iterators for efficient looping |
| 3 | ======================================================================= |
| 4 | |
| 5 | .. module:: itertools |
| 6 | :synopsis: Functions creating iterators for efficient looping. |
| 7 | .. moduleauthor:: Raymond Hettinger <python@rcn.com> |
| 8 | .. sectionauthor:: Raymond Hettinger <python@rcn.com> |
| 9 | |
| 10 | |
| 11 | .. versionadded:: 2.3 |
| 12 | |
Georg Brandl | e7a0990 | 2007-10-21 12:10:28 +0000 | [diff] [blame] | 13 | This module implements a number of :term:`iterator` building blocks inspired by |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 14 | constructs from the Haskell and SML programming languages. Each has been recast |
| 15 | in a form suitable for Python. |
| 16 | |
| 17 | The module standardizes a core set of fast, memory efficient tools that are |
| 18 | useful by themselves or in combination. Standardization helps avoid the |
| 19 | readability and reliability problems which arise when many different individuals |
| 20 | create their own slightly varying implementations, each with their own quirks |
| 21 | and naming conventions. |
| 22 | |
| 23 | The tools are designed to combine readily with one another. This makes it easy |
| 24 | to construct more specialized tools succinctly and efficiently in pure Python. |
| 25 | |
| 26 | For instance, SML provides a tabulation tool: ``tabulate(f)`` which produces a |
| 27 | sequence ``f(0), f(1), ...``. This toolbox provides :func:`imap` and |
| 28 | :func:`count` which can be combined to form ``imap(f, count())`` and produce an |
| 29 | equivalent result. |
| 30 | |
| 31 | Likewise, the functional tools are designed to work well with the high-speed |
| 32 | functions provided by the :mod:`operator` module. |
| 33 | |
| 34 | The module author welcomes suggestions for other basic building blocks to be |
| 35 | added to future versions of the module. |
| 36 | |
| 37 | Whether cast in pure python form or compiled code, tools that use iterators are |
| 38 | more memory efficient (and faster) than their list based counterparts. Adopting |
| 39 | the principles of just-in-time manufacturing, they create data when and where |
| 40 | needed instead of consuming memory with the computer equivalent of "inventory". |
| 41 | |
| 42 | The performance advantage of iterators becomes more acute as the number of |
| 43 | elements increases -- at some point, lists grow large enough to severely impact |
| 44 | memory cache performance and start running slowly. |
| 45 | |
| 46 | |
| 47 | .. seealso:: |
| 48 | |
| 49 | The Standard ML Basis Library, `The Standard ML Basis Library |
| 50 | <http://www.standardml.org/Basis/>`_. |
| 51 | |
| 52 | Haskell, A Purely Functional Language, `Definition of Haskell and the Standard |
| 53 | Libraries <http://www.haskell.org/definition/>`_. |
| 54 | |
| 55 | |
| 56 | .. _itertools-functions: |
| 57 | |
| 58 | Itertool functions |
| 59 | ------------------ |
| 60 | |
| 61 | The following module functions all construct and return iterators. Some provide |
| 62 | streams of infinite length, so they should only be accessed by functions or |
| 63 | loops that truncate the stream. |
| 64 | |
| 65 | |
| 66 | .. function:: chain(*iterables) |
| 67 | |
| 68 | Make an iterator that returns elements from the first iterable until it is |
| 69 | exhausted, then proceeds to the next iterable, until all of the iterables are |
| 70 | exhausted. Used for treating consecutive sequences as a single sequence. |
| 71 | Equivalent to:: |
| 72 | |
| 73 | def chain(*iterables): |
| 74 | for it in iterables: |
| 75 | for element in it: |
| 76 | yield element |
| 77 | |
| 78 | |
Raymond Hettinger | 330958e | 2008-02-28 19:41:24 +0000 | [diff] [blame] | 79 | .. function:: itertools.chain.from_iterable(iterable) |
| 80 | |
| 81 | Alternate constructor for :func:`chain`. Gets chained inputs from a |
| 82 | single iterable argument that is evaluated lazily. Equivalent to:: |
| 83 | |
| 84 | @classmethod |
| 85 | def from_iterable(iterables): |
| 86 | for it in iterables: |
| 87 | for element in it: |
| 88 | yield element |
| 89 | |
| 90 | .. versionadded:: 2.6 |
| 91 | |
Raymond Hettinger | 3fa41d5 | 2008-02-26 02:46:54 +0000 | [diff] [blame] | 92 | .. function:: combinations(iterable, r) |
| 93 | |
| 94 | Return successive *r* length combinations of elements in the *iterable*. |
| 95 | |
Raymond Hettinger | 330958e | 2008-02-28 19:41:24 +0000 | [diff] [blame] | 96 | Combinations are emitted in lexicographic sort order. So, if the |
Raymond Hettinger | 3fa41d5 | 2008-02-26 02:46:54 +0000 | [diff] [blame] | 97 | input *iterable* is sorted, the combination tuples will be produced |
| 98 | in sorted order. |
| 99 | |
| 100 | Elements are treated as unique based on their position, not on their |
| 101 | value. So if the input elements are unique, there will be no repeat |
Raymond Hettinger | 330958e | 2008-02-28 19:41:24 +0000 | [diff] [blame] | 102 | values in each combination. |
Raymond Hettinger | 3fa41d5 | 2008-02-26 02:46:54 +0000 | [diff] [blame] | 103 | |
| 104 | Each result tuple is ordered to match the input order. So, every |
| 105 | combination is a subsequence of the input *iterable*. |
| 106 | |
| 107 | Example: ``combinations(range(4), 3) --> (0,1,2), (0,1,3), (0,2,3), (1,2,3)`` |
| 108 | |
| 109 | Equivalent to:: |
| 110 | |
| 111 | def combinations(iterable, r): |
| 112 | pool = tuple(iterable) |
Raymond Hettinger | 93e804d | 2008-02-26 23:40:50 +0000 | [diff] [blame] | 113 | n = len(pool) |
| 114 | assert 0 <= r <= n |
| 115 | vec = range(r) |
| 116 | yield tuple(pool[i] for i in vec) |
| 117 | while 1: |
| 118 | for i in reversed(range(r)): |
Raymond Hettinger | c105289 | 2008-02-27 01:44:34 +0000 | [diff] [blame] | 119 | if vec[i] != i + n - r: |
| 120 | break |
Raymond Hettinger | 93e804d | 2008-02-26 23:40:50 +0000 | [diff] [blame] | 121 | else: |
| 122 | return |
Raymond Hettinger | c105289 | 2008-02-27 01:44:34 +0000 | [diff] [blame] | 123 | vec[i] += 1 |
| 124 | for j in range(i+1, r): |
| 125 | vec[j] = vec[j-1] + 1 |
| 126 | yield tuple(pool[i] for i in vec) |
Raymond Hettinger | 3fa41d5 | 2008-02-26 02:46:54 +0000 | [diff] [blame] | 127 | |
| 128 | .. versionadded:: 2.6 |
| 129 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 130 | .. function:: count([n]) |
| 131 | |
| 132 | Make an iterator that returns consecutive integers starting with *n*. If not |
Raymond Hettinger | 50e90e2 | 2007-10-04 00:20:27 +0000 | [diff] [blame] | 133 | specified *n* defaults to zero. Often used as an argument to :func:`imap` to |
| 134 | generate consecutive data points. Also, used with :func:`izip` to add sequence |
| 135 | numbers. Equivalent to:: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 136 | |
| 137 | def count(n=0): |
| 138 | while True: |
| 139 | yield n |
| 140 | n += 1 |
| 141 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 142 | |
| 143 | .. function:: cycle(iterable) |
| 144 | |
| 145 | Make an iterator returning elements from the iterable and saving a copy of each. |
| 146 | When the iterable is exhausted, return elements from the saved copy. Repeats |
| 147 | indefinitely. Equivalent to:: |
| 148 | |
| 149 | def cycle(iterable): |
| 150 | saved = [] |
| 151 | for element in iterable: |
| 152 | yield element |
| 153 | saved.append(element) |
| 154 | while saved: |
| 155 | for element in saved: |
| 156 | yield element |
| 157 | |
| 158 | Note, this member of the toolkit may require significant auxiliary storage |
| 159 | (depending on the length of the iterable). |
| 160 | |
| 161 | |
| 162 | .. function:: dropwhile(predicate, iterable) |
| 163 | |
| 164 | Make an iterator that drops elements from the iterable as long as the predicate |
| 165 | is true; afterwards, returns every element. Note, the iterator does not produce |
| 166 | *any* output until the predicate first becomes false, so it may have a lengthy |
| 167 | start-up time. Equivalent to:: |
| 168 | |
| 169 | def dropwhile(predicate, iterable): |
| 170 | iterable = iter(iterable) |
| 171 | for x in iterable: |
| 172 | if not predicate(x): |
| 173 | yield x |
| 174 | break |
| 175 | for x in iterable: |
| 176 | yield x |
| 177 | |
| 178 | |
| 179 | .. function:: groupby(iterable[, key]) |
| 180 | |
| 181 | Make an iterator that returns consecutive keys and groups from the *iterable*. |
| 182 | The *key* is a function computing a key value for each element. If not |
| 183 | specified or is ``None``, *key* defaults to an identity function and returns |
| 184 | the element unchanged. Generally, the iterable needs to already be sorted on |
| 185 | the same key function. |
| 186 | |
| 187 | The operation of :func:`groupby` is similar to the ``uniq`` filter in Unix. It |
| 188 | generates a break or new group every time the value of the key function changes |
| 189 | (which is why it is usually necessary to have sorted the data using the same key |
| 190 | function). That behavior differs from SQL's GROUP BY which aggregates common |
| 191 | elements regardless of their input order. |
| 192 | |
| 193 | The returned group is itself an iterator that shares the underlying iterable |
| 194 | with :func:`groupby`. Because the source is shared, when the :func:`groupby` |
| 195 | object is advanced, the previous group is no longer visible. So, if that data |
| 196 | is needed later, it should be stored as a list:: |
| 197 | |
| 198 | groups = [] |
| 199 | uniquekeys = [] |
| 200 | data = sorted(data, key=keyfunc) |
| 201 | for k, g in groupby(data, keyfunc): |
| 202 | groups.append(list(g)) # Store group iterator as a list |
| 203 | uniquekeys.append(k) |
| 204 | |
| 205 | :func:`groupby` is equivalent to:: |
| 206 | |
| 207 | class groupby(object): |
| 208 | def __init__(self, iterable, key=None): |
| 209 | if key is None: |
| 210 | key = lambda x: x |
| 211 | self.keyfunc = key |
| 212 | self.it = iter(iterable) |
Raymond Hettinger | 81a885a | 2007-12-29 22:16:24 +0000 | [diff] [blame] | 213 | self.tgtkey = self.currkey = self.currvalue = object() |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 214 | def __iter__(self): |
| 215 | return self |
| 216 | def next(self): |
| 217 | while self.currkey == self.tgtkey: |
| 218 | self.currvalue = self.it.next() # Exit on StopIteration |
| 219 | self.currkey = self.keyfunc(self.currvalue) |
| 220 | self.tgtkey = self.currkey |
| 221 | return (self.currkey, self._grouper(self.tgtkey)) |
| 222 | def _grouper(self, tgtkey): |
| 223 | while self.currkey == tgtkey: |
| 224 | yield self.currvalue |
| 225 | self.currvalue = self.it.next() # Exit on StopIteration |
| 226 | self.currkey = self.keyfunc(self.currvalue) |
| 227 | |
| 228 | .. versionadded:: 2.4 |
| 229 | |
| 230 | |
| 231 | .. function:: ifilter(predicate, iterable) |
| 232 | |
| 233 | Make an iterator that filters elements from iterable returning only those for |
| 234 | which the predicate is ``True``. If *predicate* is ``None``, return the items |
| 235 | that are true. Equivalent to:: |
| 236 | |
| 237 | def ifilter(predicate, iterable): |
| 238 | if predicate is None: |
| 239 | predicate = bool |
| 240 | for x in iterable: |
| 241 | if predicate(x): |
| 242 | yield x |
| 243 | |
| 244 | |
| 245 | .. function:: ifilterfalse(predicate, iterable) |
| 246 | |
| 247 | Make an iterator that filters elements from iterable returning only those for |
| 248 | which the predicate is ``False``. If *predicate* is ``None``, return the items |
| 249 | that are false. Equivalent to:: |
| 250 | |
| 251 | def ifilterfalse(predicate, iterable): |
| 252 | if predicate is None: |
| 253 | predicate = bool |
| 254 | for x in iterable: |
| 255 | if not predicate(x): |
| 256 | yield x |
| 257 | |
| 258 | |
| 259 | .. function:: imap(function, *iterables) |
| 260 | |
| 261 | Make an iterator that computes the function using arguments from each of the |
| 262 | iterables. If *function* is set to ``None``, then :func:`imap` returns the |
| 263 | arguments as a tuple. Like :func:`map` but stops when the shortest iterable is |
| 264 | exhausted instead of filling in ``None`` for shorter iterables. The reason for |
| 265 | the difference is that infinite iterator arguments are typically an error for |
| 266 | :func:`map` (because the output is fully evaluated) but represent a common and |
| 267 | useful way of supplying arguments to :func:`imap`. Equivalent to:: |
| 268 | |
| 269 | def imap(function, *iterables): |
| 270 | iterables = map(iter, iterables) |
| 271 | while True: |
Raymond Hettinger | 2dec48d | 2008-01-22 22:09:26 +0000 | [diff] [blame] | 272 | args = [it.next() for it in iterables] |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 273 | if function is None: |
| 274 | yield tuple(args) |
| 275 | else: |
| 276 | yield function(*args) |
| 277 | |
| 278 | |
| 279 | .. function:: islice(iterable, [start,] stop [, step]) |
| 280 | |
| 281 | Make an iterator that returns selected elements from the iterable. If *start* is |
| 282 | non-zero, then elements from the iterable are skipped until start is reached. |
| 283 | Afterward, elements are returned consecutively unless *step* is set higher than |
| 284 | one which results in items being skipped. If *stop* is ``None``, then iteration |
| 285 | continues until the iterator is exhausted, if at all; otherwise, it stops at the |
| 286 | specified position. Unlike regular slicing, :func:`islice` does not support |
| 287 | negative values for *start*, *stop*, or *step*. Can be used to extract related |
| 288 | fields from data where the internal structure has been flattened (for example, a |
| 289 | multi-line report may list a name field on every third line). Equivalent to:: |
| 290 | |
| 291 | def islice(iterable, *args): |
| 292 | s = slice(*args) |
| 293 | it = iter(xrange(s.start or 0, s.stop or sys.maxint, s.step or 1)) |
| 294 | nexti = it.next() |
| 295 | for i, element in enumerate(iterable): |
| 296 | if i == nexti: |
| 297 | yield element |
| 298 | nexti = it.next() |
| 299 | |
| 300 | If *start* is ``None``, then iteration starts at zero. If *step* is ``None``, |
| 301 | then the step defaults to one. |
| 302 | |
| 303 | .. versionchanged:: 2.5 |
| 304 | accept ``None`` values for default *start* and *step*. |
| 305 | |
| 306 | |
| 307 | .. function:: izip(*iterables) |
| 308 | |
| 309 | Make an iterator that aggregates elements from each of the iterables. Like |
| 310 | :func:`zip` except that it returns an iterator instead of a list. Used for |
| 311 | lock-step iteration over several iterables at a time. Equivalent to:: |
| 312 | |
| 313 | def izip(*iterables): |
| 314 | iterables = map(iter, iterables) |
| 315 | while iterables: |
| 316 | result = [it.next() for it in iterables] |
| 317 | yield tuple(result) |
| 318 | |
| 319 | .. versionchanged:: 2.4 |
| 320 | When no iterables are specified, returns a zero length iterator instead of |
| 321 | raising a :exc:`TypeError` exception. |
| 322 | |
Raymond Hettinger | 48c6293 | 2008-01-22 19:51:41 +0000 | [diff] [blame] | 323 | The left-to-right evaluation order of the iterables is guaranteed. This |
| 324 | makes possible an idiom for clustering a data series into n-length groups |
| 325 | using ``izip(*[iter(s)]*n)``. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 326 | |
Raymond Hettinger | 48c6293 | 2008-01-22 19:51:41 +0000 | [diff] [blame] | 327 | :func:`izip` should only be used with unequal length inputs when you don't |
| 328 | care about trailing, unmatched values from the longer iterables. If those |
| 329 | values are important, use :func:`izip_longest` instead. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 330 | |
| 331 | |
| 332 | .. function:: izip_longest(*iterables[, fillvalue]) |
| 333 | |
| 334 | Make an iterator that aggregates elements from each of the iterables. If the |
| 335 | iterables are of uneven length, missing values are filled-in with *fillvalue*. |
| 336 | Iteration continues until the longest iterable is exhausted. Equivalent to:: |
| 337 | |
| 338 | def izip_longest(*args, **kwds): |
| 339 | fillvalue = kwds.get('fillvalue') |
| 340 | def sentinel(counter = ([fillvalue]*(len(args)-1)).pop): |
| 341 | yield counter() # yields the fillvalue, or raises IndexError |
| 342 | fillers = repeat(fillvalue) |
| 343 | iters = [chain(it, sentinel(), fillers) for it in args] |
| 344 | try: |
| 345 | for tup in izip(*iters): |
| 346 | yield tup |
| 347 | except IndexError: |
| 348 | pass |
| 349 | |
| 350 | If one of the iterables is potentially infinite, then the :func:`izip_longest` |
| 351 | function should be wrapped with something that limits the number of calls (for |
| 352 | example :func:`islice` or :func:`takewhile`). |
| 353 | |
| 354 | .. versionadded:: 2.6 |
| 355 | |
Raymond Hettinger | 330958e | 2008-02-28 19:41:24 +0000 | [diff] [blame] | 356 | .. function:: permutations(iterable[, r]) |
| 357 | |
| 358 | Return successive *r* length permutations of elements in the *iterable*. |
| 359 | |
| 360 | If *r* is not specified or is ``None``, then *r* defaults to the length |
| 361 | of the *iterable* and all possible full-length permutations |
| 362 | are generated. |
| 363 | |
| 364 | Permutations are emitted in lexicographic sort order. So, if the |
| 365 | input *iterable* is sorted, the permutation tuples will be produced |
| 366 | in sorted order. |
| 367 | |
| 368 | Elements are treated as unique based on their position, not on their |
| 369 | value. So if the input elements are unique, there will be no repeat |
| 370 | values in each permutation. |
| 371 | |
| 372 | Example: ``permutations(range(3),2) --> (1,2) (1,3) (2,1) (2,3) (3,1) (3,2)`` |
| 373 | |
| 374 | .. versionadded:: 2.6 |
| 375 | |
Raymond Hettinger | 18750ab | 2008-02-28 09:23:48 +0000 | [diff] [blame] | 376 | .. function:: product(*iterables[, repeat]) |
Raymond Hettinger | c5705a8 | 2008-02-22 19:50:06 +0000 | [diff] [blame] | 377 | |
| 378 | Cartesian product of input iterables. |
| 379 | |
| 380 | Equivalent to nested for-loops in a generator expression. For example, |
| 381 | ``product(A, B)`` returns the same as ``((x,y) for x in A for y in B)``. |
| 382 | |
| 383 | The leftmost iterators are in the outermost for-loop, so the output tuples |
| 384 | cycle in a manner similar to an odometer (with the rightmost element |
Raymond Hettinger | 3fa41d5 | 2008-02-26 02:46:54 +0000 | [diff] [blame] | 385 | changing on every iteration). This results in a lexicographic ordering |
| 386 | so that if the inputs iterables are sorted, the product tuples are emitted |
| 387 | in sorted order. |
Raymond Hettinger | c5705a8 | 2008-02-22 19:50:06 +0000 | [diff] [blame] | 388 | |
Raymond Hettinger | 18750ab | 2008-02-28 09:23:48 +0000 | [diff] [blame] | 389 | To compute the product of an iterable with itself, specify the number of |
| 390 | repetitions with the optional *repeat* keyword argument. For example, |
| 391 | ``product(A, repeat=4)`` means the same as ``product(A, A, A, A)``. |
| 392 | |
Raymond Hettinger | 3fa41d5 | 2008-02-26 02:46:54 +0000 | [diff] [blame] | 393 | Equivalent to the following except that the actual implementation does not |
| 394 | build-up intermediate results in memory:: |
Raymond Hettinger | c5705a8 | 2008-02-22 19:50:06 +0000 | [diff] [blame] | 395 | |
Raymond Hettinger | 18750ab | 2008-02-28 09:23:48 +0000 | [diff] [blame] | 396 | def product(*args, **kwds): |
| 397 | pools = map(tuple, args) * kwds.get('repeat', 1) |
Raymond Hettinger | c5705a8 | 2008-02-22 19:50:06 +0000 | [diff] [blame] | 398 | if pools: |
| 399 | result = [[]] |
| 400 | for pool in pools: |
| 401 | result = [x+[y] for x in result for y in pool] |
| 402 | for prod in result: |
| 403 | yield tuple(prod) |
| 404 | |
| 405 | .. versionadded:: 2.6 |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 406 | |
| 407 | .. function:: repeat(object[, times]) |
| 408 | |
| 409 | Make an iterator that returns *object* over and over again. Runs indefinitely |
| 410 | unless the *times* argument is specified. Used as argument to :func:`imap` for |
| 411 | invariant parameters to the called function. Also used with :func:`izip` to |
| 412 | create an invariant part of a tuple record. Equivalent to:: |
| 413 | |
| 414 | def repeat(object, times=None): |
| 415 | if times is None: |
| 416 | while True: |
| 417 | yield object |
| 418 | else: |
| 419 | for i in xrange(times): |
| 420 | yield object |
| 421 | |
| 422 | |
| 423 | .. function:: starmap(function, iterable) |
| 424 | |
Raymond Hettinger | 4731709 | 2008-01-17 03:02:14 +0000 | [diff] [blame] | 425 | Make an iterator that computes the function using arguments obtained from |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 426 | the iterable. Used instead of :func:`imap` when argument parameters are already |
| 427 | grouped in tuples from a single iterable (the data has been "pre-zipped"). The |
| 428 | difference between :func:`imap` and :func:`starmap` parallels the distinction |
| 429 | between ``function(a,b)`` and ``function(*c)``. Equivalent to:: |
| 430 | |
| 431 | def starmap(function, iterable): |
Raymond Hettinger | 4731709 | 2008-01-17 03:02:14 +0000 | [diff] [blame] | 432 | for args in iterable: |
| 433 | yield function(*args) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 434 | |
Raymond Hettinger | 4731709 | 2008-01-17 03:02:14 +0000 | [diff] [blame] | 435 | .. versionchanged:: 2.6 |
| 436 | Previously, :func:`starmap` required the function arguments to be tuples. |
| 437 | Now, any iterable is allowed. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 438 | |
| 439 | .. function:: takewhile(predicate, iterable) |
| 440 | |
| 441 | Make an iterator that returns elements from the iterable as long as the |
| 442 | predicate is true. Equivalent to:: |
| 443 | |
| 444 | def takewhile(predicate, iterable): |
| 445 | for x in iterable: |
| 446 | if predicate(x): |
| 447 | yield x |
| 448 | else: |
| 449 | break |
| 450 | |
| 451 | |
| 452 | .. function:: tee(iterable[, n=2]) |
| 453 | |
| 454 | Return *n* independent iterators from a single iterable. The case where ``n==2`` |
| 455 | is equivalent to:: |
| 456 | |
| 457 | def tee(iterable): |
Raymond Hettinger | 5d332bb | 2007-12-29 22:09:34 +0000 | [diff] [blame] | 458 | def gen(next, data={}): |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 459 | for i in count(): |
Raymond Hettinger | 5d332bb | 2007-12-29 22:09:34 +0000 | [diff] [blame] | 460 | if i in data: |
| 461 | yield data.pop(i) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 462 | else: |
Raymond Hettinger | 5d332bb | 2007-12-29 22:09:34 +0000 | [diff] [blame] | 463 | data[i] = next() |
| 464 | yield data[i] |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 465 | it = iter(iterable) |
Raymond Hettinger | 5d332bb | 2007-12-29 22:09:34 +0000 | [diff] [blame] | 466 | return gen(it.next), gen(it.next) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 467 | |
| 468 | Note, once :func:`tee` has made a split, the original *iterable* should not be |
| 469 | used anywhere else; otherwise, the *iterable* could get advanced without the tee |
| 470 | objects being informed. |
| 471 | |
| 472 | Note, this member of the toolkit may require significant auxiliary storage |
| 473 | (depending on how much temporary data needs to be stored). In general, if one |
| 474 | iterator is going to use most or all of the data before the other iterator, it |
| 475 | is faster to use :func:`list` instead of :func:`tee`. |
| 476 | |
| 477 | .. versionadded:: 2.4 |
| 478 | |
| 479 | |
| 480 | .. _itertools-example: |
| 481 | |
| 482 | Examples |
| 483 | -------- |
| 484 | |
| 485 | The following examples show common uses for each tool and demonstrate ways they |
| 486 | can be combined. :: |
| 487 | |
| 488 | >>> amounts = [120.15, 764.05, 823.14] |
| 489 | >>> for checknum, amount in izip(count(1200), amounts): |
| 490 | ... print 'Check %d is for $%.2f' % (checknum, amount) |
| 491 | ... |
| 492 | Check 1200 is for $120.15 |
| 493 | Check 1201 is for $764.05 |
| 494 | Check 1202 is for $823.14 |
| 495 | |
| 496 | >>> import operator |
| 497 | >>> for cube in imap(operator.pow, xrange(1,5), repeat(3)): |
| 498 | ... print cube |
| 499 | ... |
| 500 | 1 |
| 501 | 8 |
| 502 | 27 |
| 503 | 64 |
| 504 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 505 | # Show a dictionary sorted and grouped by value |
| 506 | >>> from operator import itemgetter |
| 507 | >>> d = dict(a=1, b=2, c=1, d=2, e=1, f=2, g=3) |
| 508 | >>> di = sorted(d.iteritems(), key=itemgetter(1)) |
| 509 | >>> for k, g in groupby(di, key=itemgetter(1)): |
| 510 | ... print k, map(itemgetter(0), g) |
| 511 | ... |
| 512 | 1 ['a', 'c', 'e'] |
| 513 | 2 ['b', 'd', 'f'] |
| 514 | 3 ['g'] |
| 515 | |
| 516 | # Find runs of consecutive numbers using groupby. The key to the solution |
| 517 | # is differencing with a range so that consecutive numbers all appear in |
| 518 | # same group. |
| 519 | >>> data = [ 1, 4,5,6, 10, 15,16,17,18, 22, 25,26,27,28] |
| 520 | >>> for k, g in groupby(enumerate(data), lambda (i,x):i-x): |
| 521 | ... print map(operator.itemgetter(1), g) |
| 522 | ... |
| 523 | [1] |
| 524 | [4, 5, 6] |
| 525 | [10] |
| 526 | [15, 16, 17, 18] |
| 527 | [22] |
| 528 | [25, 26, 27, 28] |
| 529 | |
| 530 | |
| 531 | |
| 532 | .. _itertools-recipes: |
| 533 | |
| 534 | Recipes |
| 535 | ------- |
| 536 | |
| 537 | This section shows recipes for creating an extended toolset using the existing |
| 538 | itertools as building blocks. |
| 539 | |
| 540 | The extended tools offer the same high performance as the underlying toolset. |
| 541 | The superior memory performance is kept by processing elements one at a time |
| 542 | rather than bringing the whole iterable into memory all at once. Code volume is |
| 543 | kept small by linking the tools together in a functional style which helps |
| 544 | eliminate temporary variables. High speed is retained by preferring |
Georg Brandl | cf3fb25 | 2007-10-21 10:52:38 +0000 | [diff] [blame] | 545 | "vectorized" building blocks over the use of for-loops and :term:`generator`\s |
| 546 | which incur interpreter overhead. :: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 547 | |
| 548 | def take(n, seq): |
| 549 | return list(islice(seq, n)) |
| 550 | |
| 551 | def enumerate(iterable): |
| 552 | return izip(count(), iterable) |
| 553 | |
| 554 | def tabulate(function): |
| 555 | "Return function(0), function(1), ..." |
| 556 | return imap(function, count()) |
| 557 | |
| 558 | def iteritems(mapping): |
| 559 | return izip(mapping.iterkeys(), mapping.itervalues()) |
| 560 | |
| 561 | def nth(iterable, n): |
| 562 | "Returns the nth item or raise StopIteration" |
| 563 | return islice(iterable, n, None).next() |
| 564 | |
| 565 | def all(seq, pred=None): |
| 566 | "Returns True if pred(x) is true for every element in the iterable" |
| 567 | for elem in ifilterfalse(pred, seq): |
| 568 | return False |
| 569 | return True |
| 570 | |
| 571 | def any(seq, pred=None): |
| 572 | "Returns True if pred(x) is true for at least one element in the iterable" |
| 573 | for elem in ifilter(pred, seq): |
| 574 | return True |
| 575 | return False |
| 576 | |
| 577 | def no(seq, pred=None): |
| 578 | "Returns True if pred(x) is false for every element in the iterable" |
| 579 | for elem in ifilter(pred, seq): |
| 580 | return False |
| 581 | return True |
| 582 | |
| 583 | def quantify(seq, pred=None): |
| 584 | "Count how many times the predicate is true in the sequence" |
| 585 | return sum(imap(pred, seq)) |
| 586 | |
| 587 | def padnone(seq): |
| 588 | """Returns the sequence elements and then returns None indefinitely. |
| 589 | |
| 590 | Useful for emulating the behavior of the built-in map() function. |
| 591 | """ |
| 592 | return chain(seq, repeat(None)) |
| 593 | |
| 594 | def ncycles(seq, n): |
| 595 | "Returns the sequence elements n times" |
Raymond Hettinger | 330958e | 2008-02-28 19:41:24 +0000 | [diff] [blame] | 596 | return chain.from_iterable(repeat(seq, n)) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 597 | |
| 598 | def dotproduct(vec1, vec2): |
| 599 | return sum(imap(operator.mul, vec1, vec2)) |
| 600 | |
| 601 | def flatten(listOfLists): |
Raymond Hettinger | 330958e | 2008-02-28 19:41:24 +0000 | [diff] [blame] | 602 | return list(chain.from_iterable(listOfLists)) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 603 | |
| 604 | def repeatfunc(func, times=None, *args): |
| 605 | """Repeat calls to func with specified arguments. |
| 606 | |
| 607 | Example: repeatfunc(random.random) |
| 608 | """ |
| 609 | if times is None: |
| 610 | return starmap(func, repeat(args)) |
Raymond Hettinger | 330958e | 2008-02-28 19:41:24 +0000 | [diff] [blame] | 611 | return starmap(func, repeat(args, times)) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 612 | |
| 613 | def pairwise(iterable): |
| 614 | "s -> (s0,s1), (s1,s2), (s2, s3), ..." |
| 615 | a, b = tee(iterable) |
| 616 | try: |
| 617 | b.next() |
| 618 | except StopIteration: |
| 619 | pass |
| 620 | return izip(a, b) |
| 621 | |
| 622 | def grouper(n, iterable, padvalue=None): |
| 623 | "grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')" |
| 624 | return izip(*[chain(iterable, repeat(padvalue, n-1))]*n) |
| 625 | |
Raymond Hettinger | a44327a | 2008-01-30 22:17:31 +0000 | [diff] [blame] | 626 | def roundrobin(*iterables): |
| 627 | "roundrobin('abc', 'd', 'ef') --> 'a', 'd', 'e', 'b', 'f', 'c'" |
Raymond Hettinger | 330958e | 2008-02-28 19:41:24 +0000 | [diff] [blame] | 628 | # Recipe credited to George Sakkis |
Raymond Hettinger | a44327a | 2008-01-30 22:17:31 +0000 | [diff] [blame] | 629 | pending = len(iterables) |
| 630 | nexts = cycle(iter(it).next for it in iterables) |
| 631 | while pending: |
| 632 | try: |
| 633 | for next in nexts: |
| 634 | yield next() |
| 635 | except StopIteration: |
| 636 | pending -= 1 |
| 637 | nexts = cycle(islice(nexts, pending)) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 638 | |
Raymond Hettinger | 7832d4d | 2008-02-23 10:04:15 +0000 | [diff] [blame] | 639 | def powerset(iterable): |
Raymond Hettinger | 330958e | 2008-02-28 19:41:24 +0000 | [diff] [blame] | 640 | "powerset('ab') --> set([]), set(['a']), set(['b']), set(['a', 'b'])" |
| 641 | # Recipe credited to Eric Raymond |
| 642 | pairs = [(2**i, x) for i, x in enumerate(iterable)] |
| 643 | for n in xrange(2**len(pairs)): |
| 644 | yield set(x for m, x in pairs if m&n) |
Raymond Hettinger | 7832d4d | 2008-02-23 10:04:15 +0000 | [diff] [blame] | 645 | |