1:mod:`itertools` --- Functions creating iterators for efficient looping
2=======================================================================
3
4.. module:: itertools
5   :synopsis: Functions creating iterators for efficient looping.
6
7.. moduleauthor:: Raymond Hettinger <[email protected]>
8.. sectionauthor:: Raymond Hettinger <[email protected]>
9
10.. testsetup::
11
12   from itertools import *
13   import collections
14   import math
15   import operator
16   import random
17
18--------------
19
20This module implements a number of :term:`iterator` building blocks inspired
21by constructs from APL, Haskell, and SML.  Each has been recast in a form
22suitable for Python.
23
24The module standardizes a core set of fast, memory efficient tools that are
25useful by themselves or in combination.  Together, they form an "iterator
26algebra" making it possible to construct specialized tools succinctly and
27efficiently in pure Python.
28
29For instance, SML provides a tabulation tool: ``tabulate(f)`` which produces a
30sequence ``f(0), f(1), ...``.  The same effect can be achieved in Python
31by combining :func:`map` and :func:`count` to form ``map(f, count())``.
32
33These tools and their built-in counterparts also work well with the high-speed
34functions in the :mod:`operator` module.  For example, the multiplication
35operator can be mapped across two vectors to form an efficient dot-product:
36``sum(starmap(operator.mul, zip(vec1, vec2, strict=True)))``.
37
38
39**Infinite iterators:**
40
41==================  =================       =================================================               =========================================
42Iterator            Arguments               Results                                                         Example
43==================  =================       =================================================               =========================================
44:func:`count`       start, [step]           start, start+step, start+2*step, ...                            ``count(10) --> 10 11 12 13 14 ...``
45:func:`cycle`       p                       p0, p1, ... plast, p0, p1, ...                                  ``cycle('ABCD') --> A B C D A B C D ...``
46:func:`repeat`      elem [,n]               elem, elem, elem, ... endlessly or up to n times                ``repeat(10, 3) --> 10 10 10``
47==================  =================       =================================================               =========================================
48
49**Iterators terminating on the shortest input sequence:**
50
51============================    ============================    =================================================   =============================================================
52Iterator                        Arguments                       Results                                             Example
53============================    ============================    =================================================   =============================================================
54:func:`accumulate`              p [,func]                       p0, p0+p1, p0+p1+p2, ...                            ``accumulate([1,2,3,4,5]) --> 1 3 6 10 15``
55:func:`chain`                   p, q, ...                       p0, p1, ... plast, q0, q1, ...                      ``chain('ABC', 'DEF') --> A B C D E F``
56:func:`chain.from_iterable`     iterable                        p0, p1, ... plast, q0, q1, ...                      ``chain.from_iterable(['ABC', 'DEF']) --> A B C D E F``
57:func:`compress`                data, selectors                 (d[0] if s[0]), (d[1] if s[1]), ...                 ``compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F``
58:func:`dropwhile`               pred, seq                       seq[n], seq[n+1], starting when pred fails          ``dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 6 4 1``
59:func:`filterfalse`             pred, seq                       elements of seq where pred(elem) is false           ``filterfalse(lambda x: x%2, range(10)) --> 0 2 4 6 8``
60:func:`groupby`                 iterable[, key]                 sub-iterators grouped by value of key(v)
61:func:`islice`                  seq, [start,] stop [, step]     elements from seq[start:stop:step]                  ``islice('ABCDEFG', 2, None) --> C D E F G``
62:func:`pairwise`                iterable                        (p[0], p[1]), (p[1], p[2])                          ``pairwise('ABCDEFG') --> AB BC CD DE EF FG``
63:func:`starmap`                 func, seq                       func(\*seq[0]), func(\*seq[1]), ...                 ``starmap(pow, [(2,5), (3,2), (10,3)]) --> 32 9 1000``
64:func:`takewhile`               pred, seq                       seq[0], seq[1], until pred fails                    ``takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4``
65:func:`tee`                     it, n                           it1, it2, ... itn  splits one iterator into n
66:func:`zip_longest`             p, q, ...                       (p[0], q[0]), (p[1], q[1]), ...                     ``zip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-``
67============================    ============================    =================================================   =============================================================
68
69**Combinatoric iterators:**
70
71==============================================   ====================       =============================================================
72Iterator                                         Arguments                  Results
73==============================================   ====================       =============================================================
74:func:`product`                                  p, q, ... [repeat=1]       cartesian product, equivalent to a nested for-loop
75:func:`permutations`                             p[, r]                     r-length tuples, all possible orderings, no repeated elements
76:func:`combinations`                             p, r                       r-length tuples, in sorted order, no repeated elements
77:func:`combinations_with_replacement`            p, r                       r-length tuples, in sorted order, with repeated elements
78==============================================   ====================       =============================================================
79
80==============================================   =============================================================
81Examples                                         Results
82==============================================   =============================================================
83``product('ABCD', repeat=2)``                    ``AA AB AC AD BA BB BC BD CA CB CC CD DA DB DC DD``
84``permutations('ABCD', 2)``                      ``AB AC AD BA BC BD CA CB CD DA DB DC``
85``combinations('ABCD', 2)``                      ``AB AC AD BC BD CD``
86``combinations_with_replacement('ABCD', 2)``      ``AA AB AC AD BB BC BD CC CD DD``
87==============================================   =============================================================
88
89
90.. _itertools-functions:
91
92Itertool functions
93------------------
94
95The following module functions all construct and return iterators. Some provide
96streams of infinite length, so they should only be accessed by functions or
97loops that truncate the stream.
98
99.. function:: accumulate(iterable[, func, *, initial=None])
100
101    Make an iterator that returns accumulated sums, or accumulated
102    results of other binary functions (specified via the optional
103    *func* argument).
104
105    If *func* is supplied, it should be a function
106    of two arguments. Elements of the input *iterable* may be any type
107    that can be accepted as arguments to *func*. (For example, with
108    the default operation of addition, elements may be any addable
109    type including :class:`~decimal.Decimal` or
110    :class:`~fractions.Fraction`.)
111
112    Usually, the number of elements output matches the input iterable.
113    However, if the keyword argument *initial* is provided, the
114    accumulation leads off with the *initial* value so that the output
115    has one more element than the input iterable.
116
117    Roughly equivalent to::
118
119        def accumulate(iterable, func=operator.add, *, initial=None):
120            'Return running totals'
121            # accumulate([1,2,3,4,5]) --> 1 3 6 10 15
122            # accumulate([1,2,3,4,5], initial=100) --> 100 101 103 106 110 115
123            # accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120
124            it = iter(iterable)
125            total = initial
126            if initial is None:
127                try:
128                    total = next(it)
129                except StopIteration:
130                    return
131            yield total
132            for element in it:
133                total = func(total, element)
134                yield total
135
136    There are a number of uses for the *func* argument.  It can be set to
137    :func:`min` for a running minimum, :func:`max` for a running maximum, or
138    :func:`operator.mul` for a running product.  Amortization tables can be
139    built by accumulating interest and applying payments:
140
141    .. doctest::
142
143      >>> data = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]
144      >>> list(accumulate(data, operator.mul))     # running product
145      [3, 12, 72, 144, 144, 1296, 0, 0, 0, 0]
146      >>> list(accumulate(data, max))              # running maximum
147      [3, 4, 6, 6, 6, 9, 9, 9, 9, 9]
148
149      # Amortize a 5% loan of 1000 with 4 annual payments of 90
150      >>> cashflows = [1000, -90, -90, -90, -90]
151      >>> list(accumulate(cashflows, lambda bal, pmt: bal*1.05 + pmt))
152      [1000, 960.0, 918.0, 873.9000000000001, 827.5950000000001]
153
154    See :func:`functools.reduce` for a similar function that returns only the
155    final accumulated value.
156
157    .. versionadded:: 3.2
158
159    .. versionchanged:: 3.3
160       Added the optional *func* parameter.
161
162    .. versionchanged:: 3.8
163       Added the optional *initial* parameter.
164
165.. function:: chain(*iterables)
166
167   Make an iterator that returns elements from the first iterable until it is
168   exhausted, then proceeds to the next iterable, until all of the iterables are
169   exhausted.  Used for treating consecutive sequences as a single sequence.
170   Roughly equivalent to::
171
172      def chain(*iterables):
173          # chain('ABC', 'DEF') --> A B C D E F
174          for it in iterables:
175              for element in it:
176                  yield element
177
178
179.. classmethod:: chain.from_iterable(iterable)
180
181   Alternate constructor for :func:`chain`.  Gets chained inputs from a
182   single iterable argument that is evaluated lazily.  Roughly equivalent to::
183
184      def from_iterable(iterables):
185          # chain.from_iterable(['ABC', 'DEF']) --> A B C D E F
186          for it in iterables:
187              for element in it:
188                  yield element
189
190
191.. function:: combinations(iterable, r)
192
193   Return *r* length subsequences of elements from the input *iterable*.
194
195   The combination tuples are emitted in lexicographic ordering according to
196   the order of the input *iterable*. So, if the input *iterable* is sorted,
197   the output tuples will be produced in sorted order.
198
199   Elements are treated as unique based on their position, not on their
200   value.  So if the input elements are unique, there will be no repeated
201   values in each combination.
202
203   Roughly equivalent to::
204
205        def combinations(iterable, r):
206            # combinations('ABCD', 2) --> AB AC AD BC BD CD
207            # combinations(range(4), 3) --> 012 013 023 123
208            pool = tuple(iterable)
209            n = len(pool)
210            if r > n:
211                return
212            indices = list(range(r))
213            yield tuple(pool[i] for i in indices)
214            while True:
215                for i in reversed(range(r)):
216                    if indices[i] != i + n - r:
217                        break
218                else:
219                    return
220                indices[i] += 1
221                for j in range(i+1, r):
222                    indices[j] = indices[j-1] + 1
223                yield tuple(pool[i] for i in indices)
224
225   The code for :func:`combinations` can be also expressed as a subsequence
226   of :func:`permutations` after filtering entries where the elements are not
227   in sorted order (according to their position in the input pool)::
228
229        def combinations(iterable, r):
230            pool = tuple(iterable)
231            n = len(pool)
232            for indices in permutations(range(n), r):
233                if sorted(indices) == list(indices):
234                    yield tuple(pool[i] for i in indices)
235
236   The number of items returned is ``n! / r! / (n-r)!`` when ``0 <= r <= n``
237   or zero when ``r > n``.
238
239.. function:: combinations_with_replacement(iterable, r)
240
241   Return *r* length subsequences of elements from the input *iterable*
242   allowing individual elements to be repeated more than once.
243
244   The combination tuples are emitted in lexicographic ordering according to
245   the order of the input *iterable*. So, if the input *iterable* is sorted,
246   the output tuples will be produced in sorted order.
247
248   Elements are treated as unique based on their position, not on their
249   value.  So if the input elements are unique, the generated combinations
250   will also be unique.
251
252   Roughly equivalent to::
253
254        def combinations_with_replacement(iterable, r):
255            # combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC
256            pool = tuple(iterable)
257            n = len(pool)
258            if not n and r:
259                return
260            indices = [0] * r
261            yield tuple(pool[i] for i in indices)
262            while True:
263                for i in reversed(range(r)):
264                    if indices[i] != n - 1:
265                        break
266                else:
267                    return
268                indices[i:] = [indices[i] + 1] * (r - i)
269                yield tuple(pool[i] for i in indices)
270
271   The code for :func:`combinations_with_replacement` can be also expressed as
272   a subsequence of :func:`product` after filtering entries where the elements
273   are not in sorted order (according to their position in the input pool)::
274
275        def combinations_with_replacement(iterable, r):
276            pool = tuple(iterable)
277            n = len(pool)
278            for indices in product(range(n), repeat=r):
279                if sorted(indices) == list(indices):
280                    yield tuple(pool[i] for i in indices)
281
282   The number of items returned is ``(n+r-1)! / r! / (n-1)!`` when ``n > 0``.
283
284   .. versionadded:: 3.1
285
286
287.. function:: compress(data, selectors)
288
289   Make an iterator that filters elements from *data* returning only those that
290   have a corresponding element in *selectors* that evaluates to ``True``.
291   Stops when either the *data* or *selectors* iterables has been exhausted.
292   Roughly equivalent to::
293
294       def compress(data, selectors):
295           # compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F
296           return (d for d, s in zip(data, selectors) if s)
297
298   .. versionadded:: 3.1
299
300
301.. function:: count(start=0, step=1)
302
303   Make an iterator that returns evenly spaced values starting with number *start*. Often
304   used as an argument to :func:`map` to generate consecutive data points.
305   Also, used with :func:`zip` to add sequence numbers.  Roughly equivalent to::
306
307      def count(start=0, step=1):
308          # count(10) --> 10 11 12 13 14 ...
309          # count(2.5, 0.5) --> 2.5 3.0 3.5 ...
310          n = start
311          while True:
312              yield n
313              n += step
314
315   When counting with floating point numbers, better accuracy can sometimes be
316   achieved by substituting multiplicative code such as: ``(start + step * i
317   for i in count())``.
318
319   .. versionchanged:: 3.1
320      Added *step* argument and allowed non-integer arguments.
321
322.. function:: cycle(iterable)
323
324   Make an iterator returning elements from the iterable and saving a copy of each.
325   When the iterable is exhausted, return elements from the saved copy.  Repeats
326   indefinitely.  Roughly equivalent to::
327
328      def cycle(iterable):
329          # cycle('ABCD') --> A B C D A B C D A B C D ...
330          saved = []
331          for element in iterable:
332              yield element
333              saved.append(element)
334          while saved:
335              for element in saved:
336                    yield element
337
338   Note, this member of the toolkit may require significant auxiliary storage
339   (depending on the length of the iterable).
340
341
342.. function:: dropwhile(predicate, iterable)
343
344   Make an iterator that drops elements from the iterable as long as the predicate
345   is true; afterwards, returns every element.  Note, the iterator does not produce
346   *any* output until the predicate first becomes false, so it may have a lengthy
347   start-up time.  Roughly equivalent to::
348
349      def dropwhile(predicate, iterable):
350          # dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 6 4 1
351          iterable = iter(iterable)
352          for x in iterable:
353              if not predicate(x):
354                  yield x
355                  break
356          for x in iterable:
357              yield x
358
359.. function:: filterfalse(predicate, iterable)
360
361   Make an iterator that filters elements from iterable returning only those for
362   which the predicate is false. If *predicate* is ``None``, return the items
363   that are false. Roughly equivalent to::
364
365      def filterfalse(predicate, iterable):
366          # filterfalse(lambda x: x%2, range(10)) --> 0 2 4 6 8
367          if predicate is None:
368              predicate = bool
369          for x in iterable:
370              if not predicate(x):
371                  yield x
372
373
374.. function:: groupby(iterable, key=None)
375
376   Make an iterator that returns consecutive keys and groups from the *iterable*.
377   The *key* is a function computing a key value for each element.  If not
378   specified or is ``None``, *key* defaults to an identity function and returns
379   the element unchanged.  Generally, the iterable needs to already be sorted on
380   the same key function.
381
382   The operation of :func:`groupby` is similar to the ``uniq`` filter in Unix.  It
383   generates a break or new group every time the value of the key function changes
384   (which is why it is usually necessary to have sorted the data using the same key
385   function).  That behavior differs from SQL's GROUP BY which aggregates common
386   elements regardless of their input order.
387
388   The returned group is itself an iterator that shares the underlying iterable
389   with :func:`groupby`.  Because the source is shared, when the :func:`groupby`
390   object is advanced, the previous group is no longer visible.  So, if that data
391   is needed later, it should be stored as a list::
392
393      groups = []
394      uniquekeys = []
395      data = sorted(data, key=keyfunc)
396      for k, g in groupby(data, keyfunc):
397          groups.append(list(g))      # Store group iterator as a list
398          uniquekeys.append(k)
399
400   :func:`groupby` is roughly equivalent to::
401
402      class groupby:
403          # [k for k, g in groupby('AAAABBBCCDAABBB')] --> A B C D A B
404          # [list(g) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC D
405
406          def __init__(self, iterable, key=None):
407              if key is None:
408                  key = lambda x: x
409              self.keyfunc = key
410              self.it = iter(iterable)
411              self.tgtkey = self.currkey = self.currvalue = object()
412
413          def __iter__(self):
414              return self
415
416          def __next__(self):
417              self.id = object()
418              while self.currkey == self.tgtkey:
419                  self.currvalue = next(self.it)    # Exit on StopIteration
420                  self.currkey = self.keyfunc(self.currvalue)
421              self.tgtkey = self.currkey
422              return (self.currkey, self._grouper(self.tgtkey, self.id))
423
424          def _grouper(self, tgtkey, id):
425              while self.id is id and self.currkey == tgtkey:
426                  yield self.currvalue
427                  try:
428                      self.currvalue = next(self.it)
429                  except StopIteration:
430                      return
431                  self.currkey = self.keyfunc(self.currvalue)
432
433
434.. function:: islice(iterable, stop)
435              islice(iterable, start, stop[, step])
436
437   Make an iterator that returns selected elements from the iterable. If *start* is
438   non-zero, then elements from the iterable are skipped until start is reached.
439   Afterward, elements are returned consecutively unless *step* is set higher than
440   one which results in items being skipped.  If *stop* is ``None``, then iteration
441   continues until the iterator is exhausted, if at all; otherwise, it stops at the
442   specified position.
443
444   If *start* is ``None``, then iteration starts at zero. If *step* is ``None``,
445   then the step defaults to one.
446
447   Unlike regular slicing, :func:`islice` does not support negative values for
448   *start*, *stop*, or *step*.  Can be used to extract related fields from
449   data where the internal structure has been flattened (for example, a
450   multi-line report may list a name field on every third line).
451
452   Roughly equivalent to::
453
454      def islice(iterable, *args):
455          # islice('ABCDEFG', 2) --> A B
456          # islice('ABCDEFG', 2, 4) --> C D
457          # islice('ABCDEFG', 2, None) --> C D E F G
458          # islice('ABCDEFG', 0, None, 2) --> A C E G
459          s = slice(*args)
460          start, stop, step = s.start or 0, s.stop or sys.maxsize, s.step or 1
461          it = iter(range(start, stop, step))
462          try:
463              nexti = next(it)
464          except StopIteration:
465              # Consume *iterable* up to the *start* position.
466              for i, element in zip(range(start), iterable):
467                  pass
468              return
469          try:
470              for i, element in enumerate(iterable):
471                  if i == nexti:
472                      yield element
473                      nexti = next(it)
474          except StopIteration:
475              # Consume to *stop*.
476              for i, element in zip(range(i + 1, stop), iterable):
477                  pass
478
479
480.. function:: pairwise(iterable)
481
482   Return successive overlapping pairs taken from the input *iterable*.
483
484   The number of 2-tuples in the output iterator will be one fewer than the
485   number of inputs.  It will be empty if the input iterable has fewer than
486   two values.
487
488   Roughly equivalent to::
489
490        def pairwise(iterable):
491            # pairwise('ABCDEFG') --> AB BC CD DE EF FG
492            a, b = tee(iterable)
493            next(b, None)
494            return zip(a, b)
495
496   .. versionadded:: 3.10
497
498
499.. function:: permutations(iterable, r=None)
500
501   Return successive *r* length permutations of elements in the *iterable*.
502
503   If *r* is not specified or is ``None``, then *r* defaults to the length
504   of the *iterable* and all possible full-length permutations
505   are generated.
506
507   The permutation tuples are emitted in lexicographic order according to
508   the order of the input *iterable*. So, if the input *iterable* is sorted,
509   the output tuples will be produced in sorted order.
510
511   Elements are treated as unique based on their position, not on their
512   value.  So if the input elements are unique, there will be no repeated
513   values within a permutation.
514
515   Roughly equivalent to::
516
517        def permutations(iterable, r=None):
518            # permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
519            # permutations(range(3)) --> 012 021 102 120 201 210
520            pool = tuple(iterable)
521            n = len(pool)
522            r = n if r is None else r
523            if r > n:
524                return
525            indices = list(range(n))
526            cycles = list(range(n, n-r, -1))
527            yield tuple(pool[i] for i in indices[:r])
528            while n:
529                for i in reversed(range(r)):
530                    cycles[i] -= 1
531                    if cycles[i] == 0:
532                        indices[i:] = indices[i+1:] + indices[i:i+1]
533                        cycles[i] = n - i
534                    else:
535                        j = cycles[i]
536                        indices[i], indices[-j] = indices[-j], indices[i]
537                        yield tuple(pool[i] for i in indices[:r])
538                        break
539                else:
540                    return
541
542   The code for :func:`permutations` can be also expressed as a subsequence of
543   :func:`product`, filtered to exclude entries with repeated elements (those
544   from the same position in the input pool)::
545
546        def permutations(iterable, r=None):
547            pool = tuple(iterable)
548            n = len(pool)
549            r = n if r is None else r
550            for indices in product(range(n), repeat=r):
551                if len(set(indices)) == r:
552                    yield tuple(pool[i] for i in indices)
553
554   The number of items returned is ``n! / (n-r)!`` when ``0 <= r <= n``
555   or zero when ``r > n``.
556
557.. function:: product(*iterables, repeat=1)
558
559   Cartesian product of input iterables.
560
561   Roughly equivalent to nested for-loops in a generator expression. For example,
562   ``product(A, B)`` returns the same as ``((x,y) for x in A for y in B)``.
563
564   The nested loops cycle like an odometer with the rightmost element advancing
565   on every iteration.  This pattern creates a lexicographic ordering so that if
566   the input's iterables are sorted, the product tuples are emitted in sorted
567   order.
568
569   To compute the product of an iterable with itself, specify the number of
570   repetitions with the optional *repeat* keyword argument.  For example,
571   ``product(A, repeat=4)`` means the same as ``product(A, A, A, A)``.
572
573   This function is roughly equivalent to the following code, except that the
574   actual implementation does not build up intermediate results in memory::
575
576       def product(*args, repeat=1):
577           # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
578           # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
579           pools = [tuple(pool) for pool in args] * repeat
580           result = [[]]
581           for pool in pools:
582               result = [x+[y] for x in result for y in pool]
583           for prod in result:
584               yield tuple(prod)
585
586   Before :func:`product` runs, it completely consumes the input iterables,
587   keeping pools of values in memory to generate the products.  Accordingly,
588   it is only useful with finite inputs.
589
590.. function:: repeat(object[, times])
591
592   Make an iterator that returns *object* over and over again. Runs indefinitely
593   unless the *times* argument is specified.
594
595   Roughly equivalent to::
596
597      def repeat(object, times=None):
598          # repeat(10, 3) --> 10 10 10
599          if times is None:
600              while True:
601                  yield object
602          else:
603              for i in range(times):
604                  yield object
605
606   A common use for *repeat* is to supply a stream of constant values to *map*
607   or *zip*:
608
609   .. doctest::
610
611      >>> list(map(pow, range(10), repeat(2)))
612      [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
613
614.. function:: starmap(function, iterable)
615
616   Make an iterator that computes the function using arguments obtained from
617   the iterable.  Used instead of :func:`map` when argument parameters are already
618   grouped in tuples from a single iterable (when the data has been
619   "pre-zipped").
620
621   The difference between :func:`map` and :func:`starmap` parallels the
622   distinction between ``function(a,b)`` and ``function(*c)``. Roughly
623   equivalent to::
624
625      def starmap(function, iterable):
626          # starmap(pow, [(2,5), (3,2), (10,3)]) --> 32 9 1000
627          for args in iterable:
628              yield function(*args)
629
630
631.. function:: takewhile(predicate, iterable)
632
633   Make an iterator that returns elements from the iterable as long as the
634   predicate is true.  Roughly equivalent to::
635
636      def takewhile(predicate, iterable):
637          # takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4
638          for x in iterable:
639              if predicate(x):
640                  yield x
641              else:
642                  break
643
644
645.. function:: tee(iterable, n=2)
646
647   Return *n* independent iterators from a single iterable.
648
649   The following Python code helps explain what *tee* does (although the actual
650   implementation is more complex and uses only a single underlying
651   :abbr:`FIFO (first-in, first-out)` queue)::
652
653        def tee(iterable, n=2):
654            it = iter(iterable)
655            deques = [collections.deque() for i in range(n)]
656            def gen(mydeque):
657                while True:
658                    if not mydeque:             # when the local deque is empty
659                        try:
660                            newval = next(it)   # fetch a new value and
661                        except StopIteration:
662                            return
663                        for d in deques:        # load it to all the deques
664                            d.append(newval)
665                    yield mydeque.popleft()
666            return tuple(gen(d) for d in deques)
667
668   Once a :func:`tee` has been created, the original *iterable* should not be
669   used anywhere else; otherwise, the *iterable* could get advanced without
670   the tee objects being informed.
671
672   ``tee`` iterators are not threadsafe. A :exc:`RuntimeError` may be
673   raised when using simultaneously iterators returned by the same :func:`tee`
674   call, even if the original *iterable* is threadsafe.
675
676   This itertool may require significant auxiliary storage (depending on how
677   much temporary data needs to be stored). In general, if one iterator uses
678   most or all of the data before another iterator starts, it is faster to use
679   :func:`list` instead of :func:`tee`.
680
681
682.. function:: zip_longest(*iterables, fillvalue=None)
683
684   Make an iterator that aggregates elements from each of the iterables. If the
685   iterables are of uneven length, missing values are filled-in with *fillvalue*.
686   Iteration continues until the longest iterable is exhausted.  Roughly equivalent to::
687
688      def zip_longest(*args, fillvalue=None):
689          # zip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-
690          iterators = [iter(it) for it in args]
691          num_active = len(iterators)
692          if not num_active:
693              return
694          while True:
695              values = []
696              for i, it in enumerate(iterators):
697                  try:
698                      value = next(it)
699                  except StopIteration:
700                      num_active -= 1
701                      if not num_active:
702                          return
703                      iterators[i] = repeat(fillvalue)
704                      value = fillvalue
705                  values.append(value)
706              yield tuple(values)
707
708   If one of the iterables is potentially infinite, then the :func:`zip_longest`
709   function should be wrapped with something that limits the number of calls
710   (for example :func:`islice` or :func:`takewhile`).  If not specified,
711   *fillvalue* defaults to ``None``.
712
713
714.. _itertools-recipes:
715
716Itertools Recipes
717-----------------
718
719This section shows recipes for creating an extended toolset using the existing
720itertools as building blocks.
721
722The primary purpose of the itertools recipes is educational.  The recipes show
723various ways of thinking about individual tools — for example, that
724``chain.from_iterable`` is related to the concept of flattening.  The recipes
725also give ideas about ways that the tools can be combined — for example, how
726``compress()`` and ``range()`` can work together.  The recipes also show patterns
727for using itertools with the :mod:`operator` and :mod:`collections` modules as
728well as with the built-in itertools such as ``map()``, ``filter()``,
729``reversed()``, and ``enumerate()``.
730
731A secondary purpose of the recipes is to serve as an incubator.  The
732``accumulate()``, ``compress()``, and ``pairwise()`` itertools started out as
733recipes.  Currently, the ``iter_index()`` recipe is being tested to see
734whether it proves its worth.
735
736Substantially all of these recipes and many, many others can be installed from
737the `more-itertools project <https://pypi.org/project/more-itertools/>`_ found
738on the Python Package Index::
739
740    python -m pip install more-itertools
741
742Many of the recipes offer the same high performance as the underlying toolset.
743Superior memory performance is kept by processing elements one at a time
744rather than bringing the whole iterable into memory all at once. Code volume is
745kept small by linking the tools together in a functional style which helps
746eliminate temporary variables.  High speed is retained by preferring
747"vectorized" building blocks over the use of for-loops and :term:`generator`\s
748which incur interpreter overhead.
749
750.. testcode::
751
752   import collections
753   import math
754   import operator
755   import random
756
757   def take(n, iterable):
758       "Return first n items of the iterable as a list"
759       return list(islice(iterable, n))
760
761   def prepend(value, iterator):
762       "Prepend a single value in front of an iterator"
763       # prepend(1, [2, 3, 4]) --> 1 2 3 4
764       return chain([value], iterator)
765
766   def tabulate(function, start=0):
767       "Return function(0), function(1), ..."
768       return map(function, count(start))
769
770   def tail(n, iterable):
771       "Return an iterator over the last n items"
772       # tail(3, 'ABCDEFG') --> E F G
773       return iter(collections.deque(iterable, maxlen=n))
774
775   def consume(iterator, n=None):
776       "Advance the iterator n-steps ahead. If n is None, consume entirely."
777       # Use functions that consume iterators at C speed.
778       if n is None:
779           # feed the entire iterator into a zero-length deque
780           collections.deque(iterator, maxlen=0)
781       else:
782           # advance to the empty slice starting at position n
783           next(islice(iterator, n, n), None)
784
785   def nth(iterable, n, default=None):
786       "Returns the nth item or a default value"
787       return next(islice(iterable, n, None), default)
788
789   def all_equal(iterable):
790       "Returns True if all the elements are equal to each other"
791       g = groupby(iterable)
792       return next(g, True) and not next(g, False)
793
794   def quantify(iterable, pred=bool):
795       "Count how many times the predicate is True"
796       return sum(map(pred, iterable))
797
798   def ncycles(iterable, n):
799       "Returns the sequence elements n times"
800       return chain.from_iterable(repeat(tuple(iterable), n))
801
802   def batched(iterable, n):
803       "Batch data into tuples of length n. The last batch may be shorter."
804       # batched('ABCDEFG', 3) --> ABC DEF G
805       if n < 1:
806           raise ValueError('n must be at least one')
807       it = iter(iterable)
808       while batch := tuple(islice(it, n)):
809           yield batch
810
811   def grouper(iterable, n, *, incomplete='fill', fillvalue=None):
812       "Collect data into non-overlapping fixed-length chunks or blocks"
813       # grouper('ABCDEFG', 3, fillvalue='x') --> ABC DEF Gxx
814       # grouper('ABCDEFG', 3, incomplete='strict') --> ABC DEF ValueError
815       # grouper('ABCDEFG', 3, incomplete='ignore') --> ABC DEF
816       args = [iter(iterable)] * n
817       if incomplete == 'fill':
818           return zip_longest(*args, fillvalue=fillvalue)
819       if incomplete == 'strict':
820           return zip(*args, strict=True)
821       if incomplete == 'ignore':
822           return zip(*args)
823       else:
824           raise ValueError('Expected fill, strict, or ignore')
825
826   def sumprod(vec1, vec2):
827       "Compute a sum of products."
828       return sum(starmap(operator.mul, zip(vec1, vec2, strict=True)))
829
830   def sum_of_squares(it):
831       "Add up the squares of the input values."
832       # sum_of_squares([10, 20, 30]) -> 1400
833       return sumprod(*tee(it))
834
835   def transpose(it):
836       "Swap the rows and columns of the input."
837       # transpose([(1, 2, 3), (11, 22, 33)]) --> (1, 11) (2, 22) (3, 33)
838       return zip(*it, strict=True)
839
840   def matmul(m1, m2):
841       "Multiply two matrices."
842       # matmul([(7, 5), (3, 5)], [[2, 5], [7, 9]]) --> (49, 80), (41, 60)
843       n = len(m2[0])
844       return batched(starmap(sumprod, product(m1, transpose(m2))), n)
845
846   def convolve(signal, kernel):
847       # See:  https://betterexplained.com/articles/intuitive-convolution/
848       # convolve(data, [0.25, 0.25, 0.25, 0.25]) --> Moving average (blur)
849       # convolve(data, [1, -1]) --> 1st finite difference (1st derivative)
850       # convolve(data, [1, -2, 1]) --> 2nd finite difference (2nd derivative)
851       kernel = tuple(kernel)[::-1]
852       n = len(kernel)
853       window = collections.deque([0], maxlen=n) * n
854       for x in chain(signal, repeat(0, n-1)):
855           window.append(x)
856           yield sumprod(kernel, window)
857
858   def polynomial_from_roots(roots):
859       """Compute a polynomial's coefficients from its roots.
860
861          (x - 5) (x + 4) (x - 3)  expands to:   x³ -4x² -17x + 60
862       """
863       # polynomial_from_roots([5, -4, 3]) --> [1, -4, -17, 60]
864       expansion = [1]
865       for r in roots:
866           expansion = convolve(expansion, (1, -r))
867       return list(expansion)
868
869   def polynomial_eval(coefficients, x):
870       """Evaluate a polynomial at a specific value.
871
872       Computes with better numeric stability than Horner's method.
873       """
874       # Evaluate x³ -4x² -17x + 60 at x = 2.5
875       # polynomial_eval([1, -4, -17, 60], x=2.5) --> 8.125
876       n = len(coefficients)
877       if n == 0:
878           return x * 0  # coerce zero to the type of x
879       powers = map(pow, repeat(x), reversed(range(n)))
880       return sumprod(coefficients, powers)
881
882   def iter_index(iterable, value, start=0):
883       "Return indices where a value occurs in a sequence or iterable."
884       # iter_index('AABCADEAF', 'A') --> 0 1 4 7
885       try:
886           seq_index = iterable.index
887       except AttributeError:
888           # Slow path for general iterables
889           it = islice(iterable, start, None)
890           i = start - 1
891           try:
892               while True:
893                   yield (i := i + operator.indexOf(it, value) + 1)
894           except ValueError:
895               pass
896       else:
897           # Fast path for sequences
898           i = start - 1
899           try:
900               while True:
901                   yield (i := seq_index(value, i+1))
902           except ValueError:
903               pass
904
905   def sieve(n):
906       "Primes less than n"
907       # sieve(30) --> 2 3 5 7 11 13 17 19 23 29
908       data = bytearray((0, 1)) * (n // 2)
909       data[:3] = 0, 0, 0
910       limit = math.isqrt(n) + 1
911       for p in compress(range(limit), data):
912           data[p*p : n : p+p] = bytes(len(range(p*p, n, p+p)))
913       data[2] = 1
914       return iter_index(data, 1) if n > 2 else iter([])
915
916   def factor(n):
917       "Prime factors of n."
918       # factor(99) --> 3 3 11
919       for prime in sieve(math.isqrt(n) + 1):
920           while True:
921               quotient, remainder = divmod(n, prime)
922               if remainder:
923                   break
924               yield prime
925               n = quotient
926               if n == 1:
927                   return
928       if n > 1:
929           yield n
930
931   def flatten(list_of_lists):
932       "Flatten one level of nesting"
933       return chain.from_iterable(list_of_lists)
934
935   def repeatfunc(func, times=None, *args):
936       """Repeat calls to func with specified arguments.
937
938       Example:  repeatfunc(random.random)
939       """
940       if times is None:
941           return starmap(func, repeat(args))
942       return starmap(func, repeat(args, times))
943
944   def triplewise(iterable):
945       "Return overlapping triplets from an iterable"
946       # triplewise('ABCDEFG') --> ABC BCD CDE DEF EFG
947       for (a, _), (b, c) in pairwise(pairwise(iterable)):
948           yield a, b, c
949
950   def sliding_window(iterable, n):
951       # sliding_window('ABCDEFG', 4) --> ABCD BCDE CDEF DEFG
952       it = iter(iterable)
953       window = collections.deque(islice(it, n), maxlen=n)
954       if len(window) == n:
955           yield tuple(window)
956       for x in it:
957           window.append(x)
958           yield tuple(window)
959
960   def roundrobin(*iterables):
961       "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
962       # Recipe credited to George Sakkis
963       num_active = len(iterables)
964       nexts = cycle(iter(it).__next__ for it in iterables)
965       while num_active:
966           try:
967               for next in nexts:
968                   yield next()
969           except StopIteration:
970               # Remove the iterator we just exhausted from the cycle.
971               num_active -= 1
972               nexts = cycle(islice(nexts, num_active))
973
974   def partition(pred, iterable):
975       "Use a predicate to partition entries into false entries and true entries"
976       # partition(is_odd, range(10)) --> 0 2 4 6 8   and  1 3 5 7 9
977       t1, t2 = tee(iterable)
978       return filterfalse(pred, t1), filter(pred, t2)
979
980   def before_and_after(predicate, it):
981       """ Variant of takewhile() that allows complete
982           access to the remainder of the iterator.
983
984           >>> it = iter('ABCdEfGhI')
985           >>> all_upper, remainder = before_and_after(str.isupper, it)
986           >>> ''.join(all_upper)
987           'ABC'
988           >>> ''.join(remainder)     # takewhile() would lose the 'd'
989           'dEfGhI'
990
991           Note that the first iterator must be fully
992           consumed before the second iterator can
993           generate valid results.
994       """
995       it = iter(it)
996       transition = []
997       def true_iterator():
998           for elem in it:
999               if predicate(elem):
1000                   yield elem
1001               else:
1002                   transition.append(elem)
1003                   return
1004       def remainder_iterator():
1005           yield from transition
1006           yield from it
1007       return true_iterator(), remainder_iterator()
1008
1009   def subslices(seq):
1010       "Return all contiguous non-empty subslices of a sequence"
1011       # subslices('ABCD') --> A AB ABC ABCD B BC BCD C CD D
1012       slices = starmap(slice, combinations(range(len(seq) + 1), 2))
1013       return map(operator.getitem, repeat(seq), slices)
1014
1015   def powerset(iterable):
1016       "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
1017       s = list(iterable)
1018       return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
1019
1020   def unique_everseen(iterable, key=None):
1021       "List unique elements, preserving order. Remember all elements ever seen."
1022       # unique_everseen('AAAABBBCCDAABBB') --> A B C D
1023       # unique_everseen('ABBcCAD', str.lower) --> A B c D
1024       seen = set()
1025       if key is None:
1026           for element in filterfalse(seen.__contains__, iterable):
1027               seen.add(element)
1028               yield element
1029           # For order preserving deduplication,
1030           # a faster but non-lazy solution is:
1031           #     yield from dict.fromkeys(iterable)
1032       else:
1033           for element in iterable:
1034               k = key(element)
1035               if k not in seen:
1036                   seen.add(k)
1037                   yield element
1038           # For use cases that allow the last matching element to be returned,
1039           # a faster but non-lazy solution is:
1040           #      t1, t2 = tee(iterable)
1041           #      yield from dict(zip(map(key, t1), t2)).values()
1042
1043   def unique_justseen(iterable, key=None):
1044       "List unique elements, preserving order. Remember only the element just seen."
1045       # unique_justseen('AAAABBBCCDAABBB') --> A B C D A B
1046       # unique_justseen('ABBcCAD', str.lower) --> A B c A D
1047       return map(next, map(operator.itemgetter(1), groupby(iterable, key)))
1048
1049   def iter_except(func, exception, first=None):
1050       """ Call a function repeatedly until an exception is raised.
1051
1052       Converts a call-until-exception interface to an iterator interface.
1053       Like builtins.iter(func, sentinel) but uses an exception instead
1054       of a sentinel to end the loop.
1055
1056       Examples:
1057           iter_except(functools.partial(heappop, h), IndexError)   # priority queue iterator
1058           iter_except(d.popitem, KeyError)                         # non-blocking dict iterator
1059           iter_except(d.popleft, IndexError)                       # non-blocking deque iterator
1060           iter_except(q.get_nowait, Queue.Empty)                   # loop over a producer Queue
1061           iter_except(s.pop, KeyError)                             # non-blocking set iterator
1062
1063       """
1064       try:
1065           if first is not None:
1066               yield first()            # For database APIs needing an initial cast to db.first()
1067           while True:
1068               yield func()
1069       except exception:
1070           pass
1071
1072   def first_true(iterable, default=False, pred=None):
1073       """Returns the first true value in the iterable.
1074
1075       If no true value is found, returns *default*
1076
1077       If *pred* is not None, returns the first item
1078       for which pred(item) is true.
1079
1080       """
1081       # first_true([a,b,c], x) --> a or b or c or x
1082       # first_true([a,b], x, f) --> a if f(a) else b if f(b) else x
1083       return next(filter(pred, iterable), default)
1084
1085   def nth_combination(iterable, r, index):
1086       "Equivalent to list(combinations(iterable, r))[index]"
1087       pool = tuple(iterable)
1088       n = len(pool)
1089       c = math.comb(n, r)
1090       if index < 0:
1091           index += c
1092       if index < 0 or index >= c:
1093           raise IndexError
1094       result = []
1095       while r:
1096           c, n, r = c*r//n, n-1, r-1
1097           while index >= c:
1098               index -= c
1099               c, n = c*(n-r)//n, n-1
1100           result.append(pool[-1-n])
1101       return tuple(result)
1102
1103.. doctest::
1104    :hide:
1105
1106    These examples no longer appear in the docs but are guaranteed
1107    to keep working.
1108
1109    >>> amounts = [120.15, 764.05, 823.14]
1110    >>> for checknum, amount in zip(count(1200), amounts):
1111    ...     print('Check %d is for $%.2f' % (checknum, amount))
1112    ...
1113    Check 1200 is for $120.15
1114    Check 1201 is for $764.05
1115    Check 1202 is for $823.14
1116
1117    >>> import operator
1118    >>> for cube in map(operator.pow, range(1,4), repeat(3)):
1119    ...    print(cube)
1120    ...
1121    1
1122    8
1123    27
1124
1125    >>> reportlines = ['EuroPython', 'Roster', '', 'alex', '', 'laura', '', 'martin', '', 'walter', '', 'samuele']
1126    >>> for name in islice(reportlines, 3, None, 2):
1127    ...    print(name.title())
1128    ...
1129    Alex
1130    Laura
1131    Martin
1132    Walter
1133    Samuele
1134
1135    >>> from operator import itemgetter
1136    >>> d = dict(a=1, b=2, c=1, d=2, e=1, f=2, g=3)
1137    >>> di = sorted(sorted(d.items()), key=itemgetter(1))
1138    >>> for k, g in groupby(di, itemgetter(1)):
1139    ...     print(k, list(map(itemgetter(0), g)))
1140    ...
1141    1 ['a', 'c', 'e']
1142    2 ['b', 'd', 'f']
1143    3 ['g']
1144
1145    # Find runs of consecutive numbers using groupby.  The key to the solution
1146    # is differencing with a range so that consecutive numbers all appear in
1147    # same group.
1148    >>> data = [ 1,  4,5,6, 10, 15,16,17,18, 22, 25,26,27,28]
1149    >>> for k, g in groupby(enumerate(data), lambda t:t[0]-t[1]):
1150    ...     print(list(map(operator.itemgetter(1), g)))
1151    ...
1152    [1]
1153    [4, 5, 6]
1154    [10]
1155    [15, 16, 17, 18]
1156    [22]
1157    [25, 26, 27, 28]
1158
1159    Now, we test all of the itertool recipes
1160
1161    >>> take(10, count())
1162    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1163
1164    >>> list(prepend(1, [2, 3, 4]))
1165    [1, 2, 3, 4]
1166
1167    >>> list(enumerate('abc'))
1168    [(0, 'a'), (1, 'b'), (2, 'c')]
1169
1170    >>> list(islice(tabulate(lambda x: 2*x), 4))
1171    [0, 2, 4, 6]
1172
1173    >>> list(tail(3, 'ABCDEFG'))
1174    ['E', 'F', 'G']
1175
1176    >>> it = iter(range(10))
1177    >>> consume(it, 3)
1178    >>> next(it)
1179    3
1180    >>> consume(it)
1181    >>> next(it, 'Done')
1182    'Done'
1183
1184    >>> nth('abcde', 3)
1185    'd'
1186
1187    >>> nth('abcde', 9) is None
1188    True
1189
1190    >>> [all_equal(s) for s in ('', 'A', 'AAAA', 'AAAB', 'AAABA')]
1191    [True, True, True, False, False]
1192
1193    >>> quantify(range(99), lambda x: x%2==0)
1194    50
1195
1196    >>> quantify([True, False, False, True, True])
1197    3
1198
1199    >>> quantify(range(12), pred=lambda x: x%2==1)
1200    6
1201
1202    >>> a = [[1, 2, 3], [4, 5, 6]]
1203    >>> list(flatten(a))
1204    [1, 2, 3, 4, 5, 6]
1205
1206    >>> list(repeatfunc(pow, 5, 2, 3))
1207    [8, 8, 8, 8, 8]
1208
1209    >>> take(5, map(int, repeatfunc(random.random)))
1210    [0, 0, 0, 0, 0]
1211
1212    >>> list(ncycles('abc', 3))
1213    ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']
1214
1215    >>> sumprod([1,2,3], [4,5,6])
1216    32
1217
1218    >>> sum_of_squares([10, 20, 30])
1219    1400
1220
1221    >>> list(transpose([(1, 2, 3), (11, 22, 33)]))
1222    [(1, 11), (2, 22), (3, 33)]
1223
1224    >>> list(matmul([(7, 5), (3, 5)], [[2, 5], [7, 9]]))
1225    [(49, 80), (41, 60)]
1226    >>> list(matmul([[2, 5], [7, 9], [3, 4]], [[7, 11, 5, 4, 9], [3, 5, 2, 6, 3]]))
1227    [(29, 47, 20, 38, 33), (76, 122, 53, 82, 90), (33, 53, 23, 36, 39)]
1228
1229    >>> data = [20, 40, 24, 32, 20, 28, 16]
1230    >>> list(convolve(data, [0.25, 0.25, 0.25, 0.25]))
1231    [5.0, 15.0, 21.0, 29.0, 29.0, 26.0, 24.0, 16.0, 11.0, 4.0]
1232    >>> list(convolve(data, [1, -1]))
1233    [20, 20, -16, 8, -12, 8, -12, -16]
1234    >>> list(convolve(data, [1, -2, 1]))
1235    [20, 0, -36, 24, -20, 20, -20, -4, 16]
1236
1237    >>> polynomial_from_roots([5, -4, 3])
1238    [1, -4, -17, 60]
1239    >>> factored = lambda x: (x - 5) * (x + 4) * (x - 3)
1240    >>> expanded = lambda x: x**3 -4*x**2 -17*x + 60
1241    >>> all(factored(x) == expanded(x) for x in range(-10, 11))
1242    True
1243
1244    >>> list(iter_index('AABCADEAF', 'A'))
1245    [0, 1, 4, 7]
1246    >>> list(iter_index('AABCADEAF', 'B'))
1247    [2]
1248    >>> list(iter_index('AABCADEAF', 'X'))
1249    []
1250    >>> list(iter_index('', 'X'))
1251    []
1252    >>> list(iter_index('AABCADEAF', 'A', 1))
1253    [1, 4, 7]
1254    >>> list(iter_index(iter('AABCADEAF'), 'A', 1))
1255    [1, 4, 7]
1256    >>> list(iter_index('AABCADEAF', 'A', 2))
1257    [4, 7]
1258    >>> list(iter_index(iter('AABCADEAF'), 'A', 2))
1259    [4, 7]
1260    >>> list(iter_index('AABCADEAF', 'A', 10))
1261    []
1262    >>> list(iter_index(iter('AABCADEAF'), 'A', 10))
1263    []
1264
1265    >>> list(sieve(30))
1266    [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
1267    >>> small_primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
1268    >>> all(list(sieve(n)) == [p for p in small_primes if p < n] for n in range(101))
1269    True
1270    >>> len(list(sieve(100)))
1271    25
1272    >>> len(list(sieve(1_000)))
1273    168
1274    >>> len(list(sieve(10_000)))
1275    1229
1276    >>> len(list(sieve(100_000)))
1277    9592
1278    >>> len(list(sieve(1_000_000)))
1279    78498
1280    >>> carmichael = {561, 1105, 1729, 2465, 2821, 6601, 8911}  # https://oeis.org/A002997
1281    >>> set(sieve(10_000)).isdisjoint(carmichael)
1282    True
1283
1284    >>> list(factor(0))
1285    []
1286    >>> list(factor(1))
1287    []
1288    >>> list(factor(2))
1289    [2]
1290    >>> list(factor(3))
1291    [3]
1292    >>> list(factor(4))
1293    [2, 2]
1294    >>> list(factor(5))
1295    [5]
1296    >>> list(factor(6))
1297    [2, 3]
1298    >>> list(factor(7))
1299    [7]
1300    >>> list(factor(8))
1301    [2, 2, 2]
1302    >>> list(factor(9))
1303    [3, 3]
1304    >>> list(factor(10))
1305    [2, 5]
1306    >>> list(factor(128_884_753_939))       # large prime
1307    [128884753939]
1308    >>> list(factor(999953 * 999983))       # large semiprime
1309    [999953, 999983]
1310    >>> list(factor(6 ** 20)) == [2] * 20 + [3] * 20   # large power
1311    True
1312    >>> list(factor(909_909_090_909))       # large multiterm composite
1313    [3, 3, 7, 13, 13, 751, 113797]
1314    >>> math.prod([3, 3, 7, 13, 13, 751, 113797])
1315    909909090909
1316    >>> all(math.prod(factor(n)) == n for n in range(1, 2_000))
1317    True
1318    >>> all(set(factor(n)) <= set(sieve(n+1)) for n in range(2_000))
1319    True
1320    >>> all(list(factor(n)) == sorted(factor(n)) for n in range(2_000))
1321    True
1322
1323    >>> list(flatten([('a', 'b'), (), ('c', 'd', 'e'), ('f',), ('g', 'h', 'i')]))
1324    ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
1325
1326    >>> random.seed(85753098575309)
1327    >>> list(repeatfunc(random.random, 3))
1328    [0.16370491282496968, 0.45889608687313455, 0.3747076837820118]
1329    >>> list(repeatfunc(chr, 3, 65))
1330    ['A', 'A', 'A']
1331    >>> list(repeatfunc(pow, 3, 2, 5))
1332    [32, 32, 32]
1333
1334    >>> list(grouper('abcdefg', 3, fillvalue='x'))
1335    [('a', 'b', 'c'), ('d', 'e', 'f'), ('g', 'x', 'x')]
1336
1337    >>> it = grouper('abcdefg', 3, incomplete='strict')
1338    >>> next(it)
1339    ('a', 'b', 'c')
1340    >>> next(it)
1341    ('d', 'e', 'f')
1342    >>> next(it)
1343    Traceback (most recent call last):
1344      ...
1345    ValueError: zip() argument 2 is shorter than argument 1
1346
1347    >>> list(grouper('abcdefg', n=3, incomplete='ignore'))
1348    [('a', 'b', 'c'), ('d', 'e', 'f')]
1349
1350    >>> list(batched('ABCDEFG', 3))
1351    [('A', 'B', 'C'), ('D', 'E', 'F'), ('G',)]
1352    >>> list(batched('ABCDEF', 3))
1353    [('A', 'B', 'C'), ('D', 'E', 'F')]
1354    >>> list(batched('ABCDE', 3))
1355    [('A', 'B', 'C'), ('D', 'E')]
1356    >>> list(batched('ABCD', 3))
1357    [('A', 'B', 'C'), ('D',)]
1358    >>> list(batched('ABC', 3))
1359    [('A', 'B', 'C')]
1360    >>> list(batched('AB', 3))
1361    [('A', 'B')]
1362    >>> list(batched('A', 3))
1363    [('A',)]
1364    >>> list(batched('', 3))
1365    []
1366    >>> list(batched('ABCDEFG', 2))
1367    [('A', 'B'), ('C', 'D'), ('E', 'F'), ('G',)]
1368    >>> list(batched('ABCDEFG', 1))
1369    [('A',), ('B',), ('C',), ('D',), ('E',), ('F',), ('G',)]
1370    >>> s = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
1371    >>> all(list(flatten(batched(s[:n], 5))) == list(s[:n]) for n in range(len(s)))
1372    True
1373
1374    >>> list(triplewise('ABCDEFG'))
1375    [('A', 'B', 'C'), ('B', 'C', 'D'), ('C', 'D', 'E'), ('D', 'E', 'F'), ('E', 'F', 'G')]
1376
1377    >>> list(sliding_window('ABCDEFG', 4))
1378    [('A', 'B', 'C', 'D'), ('B', 'C', 'D', 'E'), ('C', 'D', 'E', 'F'), ('D', 'E', 'F', 'G')]
1379
1380    >>> list(roundrobin('abc', 'd', 'ef'))
1381    ['a', 'd', 'e', 'b', 'f', 'c']
1382
1383    >>> def is_odd(x):
1384    ...     return x % 2 == 1
1385
1386    >>> evens, odds = partition(is_odd, range(10))
1387    >>> list(evens)
1388    [0, 2, 4, 6, 8]
1389    >>> list(odds)
1390    [1, 3, 5, 7, 9]
1391
1392    >>> it = iter('ABCdEfGhI')
1393    >>> all_upper, remainder = before_and_after(str.isupper, it)
1394    >>> ''.join(all_upper)
1395    'ABC'
1396    >>> ''.join(remainder)
1397    'dEfGhI'
1398
1399    >>> list(subslices('ABCD'))
1400    ['A', 'AB', 'ABC', 'ABCD', 'B', 'BC', 'BCD', 'C', 'CD', 'D']
1401
1402    >>> list(powerset([1,2,3]))
1403    [(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
1404
1405    >>> all(len(list(powerset(range(n)))) == 2**n for n in range(18))
1406    True
1407
1408    >>> list(powerset('abcde')) == sorted(sorted(set(powerset('abcde'))), key=len)
1409    True
1410
1411    >>> list(unique_everseen('AAAABBBCCDAABBB'))
1412    ['A', 'B', 'C', 'D']
1413    >>> list(unique_everseen('ABBCcAD', str.lower))
1414    ['A', 'B', 'C', 'D']
1415    >>> list(unique_everseen('ABBcCAD', str.lower))
1416    ['A', 'B', 'c', 'D']
1417
1418    >>> list(unique_justseen('AAAABBBCCDAABBB'))
1419    ['A', 'B', 'C', 'D', 'A', 'B']
1420    >>> list(unique_justseen('ABBCcAD', str.lower))
1421    ['A', 'B', 'C', 'A', 'D']
1422    >>> list(unique_justseen('ABBcCAD', str.lower))
1423    ['A', 'B', 'c', 'A', 'D']
1424
1425    >>> d = dict(a=1, b=2, c=3)
1426    >>> it = iter_except(d.popitem, KeyError)
1427    >>> d['d'] = 4
1428    >>> next(it)
1429    ('d', 4)
1430    >>> next(it)
1431    ('c', 3)
1432    >>> next(it)
1433    ('b', 2)
1434    >>> d['e'] = 5
1435    >>> next(it)
1436    ('e', 5)
1437    >>> next(it)
1438    ('a', 1)
1439    >>> next(it, 'empty')
1440    'empty'
1441
1442    >>> first_true('ABC0DEF1', '9', str.isdigit)
1443    '0'
1444
1445    >>> population = 'ABCDEFGH'
1446    >>> for r in range(len(population) + 1):
1447    ...     seq = list(combinations(population, r))
1448    ...     for i in range(len(seq)):
1449    ...         assert nth_combination(population, r, i) == seq[i]
1450    ...     for i in range(-len(seq), 0):
1451    ...         assert nth_combination(population, r, i) == seq[i]
1452
1453    >>> iterable = 'abcde'
1454    >>> r = 3
1455    >>> combos = list(combinations(iterable, r))
1456    >>> all(nth_combination(iterable, r, i) == comb for i, comb in enumerate(combos))
1457    True
1458