blob: 032c0b8e8a1184bc9a7002183a5def0f1f6b0040 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001
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 Brandl9afde1c2007-11-01 20:32:30 +000011This module implements a number of :term:`iterator` building blocks inspired by
Georg Brandl116aa622007-08-15 14:28:22 +000012constructs from the Haskell and SML programming languages. Each has been recast
13in a form suitable for Python.
14
15The module standardizes a core set of fast, memory efficient tools that are
16useful by themselves or in combination. Standardization helps avoid the
17readability and reliability problems which arise when many different individuals
18create their own slightly varying implementations, each with their own quirks
19and naming conventions.
20
21The tools are designed to combine readily with one another. This makes it easy
22to construct more specialized tools succinctly and efficiently in pure Python.
23
24For instance, SML provides a tabulation tool: ``tabulate(f)`` which produces a
Raymond Hettingera6c60372008-03-13 01:26:19 +000025sequence ``f(0), f(1), ...``. But, this effect can be achieved in Python
26by combining :func:`map` and :func:`count` to form ``map(f, count())``.
Georg Brandl116aa622007-08-15 14:28:22 +000027
28Likewise, the functional tools are designed to work well with the high-speed
29functions provided by the :mod:`operator` module.
30
31The module author welcomes suggestions for other basic building blocks to be
32added to future versions of the module.
33
34Whether cast in pure python form or compiled code, tools that use iterators are
35more memory efficient (and faster) than their list based counterparts. Adopting
36the principles of just-in-time manufacturing, they create data when and where
37needed instead of consuming memory with the computer equivalent of "inventory".
38
39The performance advantage of iterators becomes more acute as the number of
40elements increases -- at some point, lists grow large enough to severely impact
41memory 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
55Itertool functions
56------------------
57
58The following module functions all construct and return iterators. Some provide
59streams of infinite length, so they should only be accessed by functions or
60loops 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 Heimes70e7ea22008-02-28 20:02:27 +000076.. 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 Heimes78644762008-03-04 23:39:23 +000089
Christian Heimes836baa52008-02-26 08:18:30 +000090.. function:: combinations(iterable, r)
91
92 Return successive *r* length combinations of elements in the *iterable*.
93
Christian Heimes70e7ea22008-02-28 20:02:27 +000094 Combinations are emitted in lexicographic sort order. So, if the
Christian Heimes836baa52008-02-26 08:18:30 +000095 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 Heimes70e7ea22008-02-28 20:02:27 +0000100 values in each combination.
Christian Heimes836baa52008-02-26 08:18:30 +0000101
102 Each result tuple is ordered to match the input order. So, every
103 combination is a subsequence of the input *iterable*.
104
Christian Heimes836baa52008-02-26 08:18:30 +0000105 Equivalent to::
106
107 def combinations(iterable, r):
Christian Heimesb558a2e2008-03-02 22:46:37 +0000108 'combinations(range(4), 3) --> (0,1,2) (0,1,3) (0,2,3) (1,2,3)'
Christian Heimes836baa52008-02-26 08:18:30 +0000109 pool = tuple(iterable)
Christian Heimes380f7f22008-02-28 11:19:05 +0000110 n = len(pool)
Christian Heimesb558a2e2008-03-02 22:46:37 +0000111 indices = range(r)
112 yield tuple(pool[i] for i in indices)
Christian Heimes380f7f22008-02-28 11:19:05 +0000113 while 1:
114 for i in reversed(range(r)):
Christian Heimesb558a2e2008-03-02 22:46:37 +0000115 if indices[i] != i + n - r:
Christian Heimes836baa52008-02-26 08:18:30 +0000116 break
Christian Heimes380f7f22008-02-28 11:19:05 +0000117 else:
118 return
Christian Heimesb558a2e2008-03-02 22:46:37 +0000119 indices[i] += 1
Christian Heimes380f7f22008-02-28 11:19:05 +0000120 for j in range(i+1, r):
Christian Heimesb558a2e2008-03-02 22:46:37 +0000121 indices[j] = indices[j-1] + 1
122 yield tuple(pool[i] for i in indices)
Christian Heimes836baa52008-02-26 08:18:30 +0000123
Christian Heimes78644762008-03-04 23:39:23 +0000124 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 Heimes836baa52008-02-26 08:18:30 +0000135 .. versionadded:: 2.6
136
Georg Brandl116aa622007-08-15 14:28:22 +0000137.. function:: count([n])
138
139 Make an iterator that returns consecutive integers starting with *n*. If not
Raymond Hettingera6c60372008-03-13 01:26:19 +0000140 specified *n* defaults to zero. Often used as an argument to :func:`map` to
Georg Brandl9afde1c2007-11-01 20:32:30 +0000141 generate consecutive data points. Also, used with :func:`izip` to add sequence
142 numbers. Equivalent to::
Georg Brandl116aa622007-08-15 14:28:22 +0000143
144 def count(n=0):
145 while True:
146 yield n
147 n += 1
148
Georg Brandl116aa622007-08-15 14:28:22 +0000149
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 Heimes5b5e81c2007-12-31 16:14:33 +0000220 self.tgtkey = self.currkey = self.currvalue = object()
Georg Brandl116aa622007-08-15 14:28:22 +0000221 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 Brandl116aa622007-08-15 14:28:22 +0000235
Georg Brandl116aa622007-08-15 14:28:22 +0000236.. 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 Brandl116aa622007-08-15 14:28:22 +0000250.. 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 Brandlf6945182008-02-01 11:56:49 +0000264 it = range(s.start or 0, s.stop or sys.maxsize, s.step or 1)
Georg Brandl116aa622007-08-15 14:28:22 +0000265 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 Brandl116aa622007-08-15 14:28:22 +0000274
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 Brandl55ac8f02007-09-01 13:51:09 +0000287 When no iterables are specified, return a zero length iterator.
Georg Brandl116aa622007-08-15 14:28:22 +0000288
Christian Heimes1af737c2008-01-23 08:24:23 +0000289 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 Brandl116aa622007-08-15 14:28:22 +0000292
Christian Heimes1af737c2008-01-23 08:24:23 +0000293 :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 Brandl116aa622007-08-15 14:28:22 +0000296
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 Brandl116aa622007-08-15 14:28:22 +0000320
Christian Heimes70e7ea22008-02-28 20:02:27 +0000321.. 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 Heimesb558a2e2008-03-02 22:46:37 +0000337 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 Heimes70e7ea22008-02-28 20:02:27 +0000360
Christian Heimes78644762008-03-04 23:39:23 +0000361 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 Heimes70e7ea22008-02-28 20:02:27 +0000373 .. versionadded:: 2.6
374
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000375.. function:: product(*iterables[, repeat])
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000376
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 Heimes78644762008-03-04 23:39:23 +0000383 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 Heimes836baa52008-02-26 08:18:30 +0000386 in sorted order.
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000387
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000388 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 Heimes78644762008-03-04 23:39:23 +0000392 This function is equivalent to the following code, except that the
393 actual implementation does not build up intermediate results in memory::
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000394
Christian Heimes9e7f1d22008-02-28 12:27:11 +0000395 def product(*args, **kwds):
396 pools = map(tuple, args) * kwds.get('repeat', 1)
Christian Heimes78644762008-03-04 23:39:23 +0000397 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 Heimes90c3d9b2008-02-23 13:18:03 +0000402
403
Georg Brandl116aa622007-08-15 14:28:22 +0000404.. function:: repeat(object[, times])
405
406 Make an iterator that returns *object* over and over again. Runs indefinitely
Raymond Hettingera6c60372008-03-13 01:26:19 +0000407 unless the *times* argument is specified. Used as argument to :func:`map` for
Georg Brandl116aa622007-08-15 14:28:22 +0000408 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 Heimes679db4a2008-01-18 09:56:22 +0000422 Make an iterator that computes the function using arguments obtained from
Raymond Hettingera6c60372008-03-13 01:26:19 +0000423 the iterable. Used instead of :func:`map` when argument parameters are already
Georg Brandl116aa622007-08-15 14:28:22 +0000424 grouped in tuples from a single iterable (the data has been "pre-zipped"). The
Raymond Hettingera6c60372008-03-13 01:26:19 +0000425 difference between :func:`map` and :func:`starmap` parallels the distinction
Georg Brandl116aa622007-08-15 14:28:22 +0000426 between ``function(a,b)`` and ``function(*c)``. Equivalent to::
427
428 def starmap(function, iterable):
Christian Heimes679db4a2008-01-18 09:56:22 +0000429 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 Brandl116aa622007-08-15 14:28:22 +0000435
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 Heimes5b5e81c2007-12-31 16:14:33 +0000456 def gen(next, data={}):
Georg Brandl116aa622007-08-15 14:28:22 +0000457 for i in count():
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000458 if i in data:
459 yield data.pop(i)
Georg Brandl116aa622007-08-15 14:28:22 +0000460 else:
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000461 data[i] = next()
462 yield data[i]
Georg Brandl116aa622007-08-15 14:28:22 +0000463 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 Brandl116aa622007-08-15 14:28:22 +0000475
476.. _itertools-example:
477
478Examples
479--------
480
481The following examples show common uses for each tool and demonstrate ways they
482can be combined. ::
483
484 >>> amounts = [120.15, 764.05, 823.14]
485 >>> for checknum, amount in izip(count(1200), amounts):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000486 ... print('Check %d is for $%.2f' % (checknum, amount))
Georg Brandl116aa622007-08-15 14:28:22 +0000487 ...
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 Hettingera6c60372008-03-13 01:26:19 +0000493 >>> for cube in map(operator.pow, range(1,5), repeat(3)):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000494 ... print(cube)
Georg Brandl116aa622007-08-15 14:28:22 +0000495 ...
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 Brandl6911e3c2007-09-04 07:15:32 +0000504 ... print(name.title())
Georg Brandl116aa622007-08-15 14:28:22 +0000505 ...
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 Drake2e748782007-09-04 17:33:11 +0000515 >>> di = sorted(d.items(), key=itemgetter(1))
Georg Brandl116aa622007-08-15 14:28:22 +0000516 >>> for k, g in groupby(di, key=itemgetter(1)):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000517 ... print(k, map(itemgetter(0), g))
Georg Brandl116aa622007-08-15 14:28:22 +0000518 ...
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 Brandl6911e3c2007-09-04 07:15:32 +0000528 ... print(map(operator.itemgetter(1), g))
Georg Brandl116aa622007-08-15 14:28:22 +0000529 ...
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
541Recipes
542-------
543
544This section shows recipes for creating an extended toolset using the existing
545itertools as building blocks.
546
547The extended tools offer the same high performance as the underlying toolset.
548The superior memory performance is kept by processing elements one at a time
549rather than bringing the whole iterable into memory all at once. Code volume is
550kept small by linking the tools together in a functional style which helps
551eliminate temporary variables. High speed is retained by preferring
Georg Brandl9afde1c2007-11-01 20:32:30 +0000552"vectorized" building blocks over the use of for-loops and :term:`generator`\s
553which incur interpreter overhead. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000554
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 Hettingera6c60372008-03-13 01:26:19 +0000563 return map(function, count())
Georg Brandl116aa622007-08-15 14:28:22 +0000564
Georg Brandl116aa622007-08-15 14:28:22 +0000565 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 Hettinger17301e92008-03-13 00:19:26 +0000577 for elem in filter(pred, seq):
Georg Brandl116aa622007-08-15 14:28:22 +0000578 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 Hettinger17301e92008-03-13 00:19:26 +0000583 for elem in filter(pred, seq):
Georg Brandl116aa622007-08-15 14:28:22 +0000584 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 Hettingera6c60372008-03-13 01:26:19 +0000589 return sum(map(pred, seq))
Georg Brandl116aa622007-08-15 14:28:22 +0000590
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 Heimes70e7ea22008-02-28 20:02:27 +0000600 return chain.from_iterable(repeat(seq, n))
Georg Brandl116aa622007-08-15 14:28:22 +0000601
602 def dotproduct(vec1, vec2):
Raymond Hettingera6c60372008-03-13 01:26:19 +0000603 return sum(map(operator.mul, vec1, vec2))
Georg Brandl116aa622007-08-15 14:28:22 +0000604
605 def flatten(listOfLists):
Christian Heimes70e7ea22008-02-28 20:02:27 +0000606 return list(chain.from_iterable(listOfLists))
Georg Brandl116aa622007-08-15 14:28:22 +0000607
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 Heimes70e7ea22008-02-28 20:02:27 +0000615 return starmap(func, repeat(args, times))
Georg Brandl116aa622007-08-15 14:28:22 +0000616
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 Heimes7b3ce6a2008-01-31 14:31:45 +0000627 def roundrobin(*iterables):
628 "roundrobin('abc', 'd', 'ef') --> 'a', 'd', 'e', 'b', 'f', 'c'"
Christian Heimes70e7ea22008-02-28 20:02:27 +0000629 # Recipe credited to George Sakkis
Christian Heimes7b3ce6a2008-01-31 14:31:45 +0000630 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 Brandl116aa622007-08-15 14:28:22 +0000639
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000640 def powerset(iterable):
Christian Heimes70e7ea22008-02-28 20:02:27 +0000641 "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 Heimes90c3d9b2008-02-23 13:18:03 +0000646