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