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