rest25/library/itertools.rst => rest262/library/itertools.rst
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
n11+.. testsetup::
12+ 
13+   from itertools import *
14+ 
11.. versionadded:: 2.3
12
n13-This module implements a number of iterator building blocks inspired by
n17+This module implements a number of :term:`iterator` building blocks inspired
14-constructs from the Haskell and SML programming languages.  Each has been recast
18+by constructs from APL, Haskell, and SML.  Each has been recast in a form
15-in a form suitable for Python.
19+suitable for Python.
16
17The module standardizes a core set of fast, memory efficient tools that are
n18-useful by themselves or in combination.  Standardization helps avoid the
n22+useful by themselves or in combination.  Together, they form an "iterator
19-readability and reliability problems which arise when many different individuals
23+algebra" making it possible to construct specialized tools succinctly and
20-create their own slightly varying implementations, each with their own quirks
24+efficiently in pure Python.
21-and naming conventions.
22- 
23-The tools are designed to combine readily with one another.  This makes it easy
24-to construct more specialized tools succinctly and efficiently in pure Python.
25
26For instance, SML provides a tabulation tool: ``tabulate(f)`` which produces a
27sequence ``f(0), f(1), ...``.  This toolbox provides :func:`imap` and
n28-:func:`count` which can be combined to form ``imap(f, count())`` and produce an
n28+:func:`count` which can be combined to form ``imap(f, count())`` to produce an
29equivalent result.
30
n31-Likewise, the functional tools are designed to work well with the high-speed
n31+These tools and their built-in counterparts also work well with the high-speed
32-functions provided by the :mod:`operator` module.
32+functions in the :mod:`operator` module.  For example, the multiplication
33+operator can be mapped across two vectors to form an efficient dot-product:
34+``sum(imap(operator.mul, vector1, vector2))``.
33
n34-The module author welcomes suggestions for other basic building blocks to be
35-added to future versions of the module.
36
n37-Whether cast in pure python form or compiled code, tools that use iterators are
n37+**Infinite Iterators:**
38-more memory efficient (and faster) than their list based counterparts. Adopting
39-the principles of just-in-time manufacturing, they create data when and where
40-needed instead of consuming memory with the computer equivalent of "inventory".
41
n42-The performance advantage of iterators becomes more acute as the number of
n39+==================  =================       =================================================               =========================================
43-elements increases -- at some point, lists grow large enough to severely impact
40+Iterator            Arguments               Results                                                         Example
44-memory cache performance and start running slowly.
41+==================  =================       =================================================               =========================================
42+:func:`count`       start                   start, start+1, start+2, ...                                    ``count(10) --> 10 11 12 13 14 ...``
43+:func:`cycle`       p                       p0, p1, ... plast, p0, p1, ...                                  ``cycle('ABCD') --> A B C D A B C D ...``
44+:func:`repeat`      elem [,n]               elem, elem, elem, ... endlessly or up to n times                ``repeat(10, 3) --> 10 10 10``
45+==================  =================       =================================================               =========================================
45
n47+**Iterators terminating on the shortest input sequence:**
46
n47-.. seealso::
n49+====================    ============================    =================================================   =============================================================
50+Iterator                Arguments                       Results                                             Example
51+====================    ============================    =================================================   =============================================================
52+:func:`chain`           p, q, ...                       p0, p1, ... plast, q0, q1, ...                      ``chain('ABC', 'DEF') --> A B C D E F``
53+: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``
54+:func:`groupby`         iterable[, keyfunc]             sub-iterators grouped by value of keyfunc(v)
55+:func:`ifilter`         pred, seq                       elements of seq where pred(elem) is True            ``ifilter(lambda x: x%2, range(10)) --> 1 3 5 7 9``
56+:func:`ifilterfalse`    pred, seq                       elements of seq where pred(elem) is False           ``ifilterfalse(lambda x: x%2, range(10)) --> 0 2 4 6 8``
57+:func:`islice`          seq, [start,] stop [, step]     elements from seq[start:stop:step]                  ``islice('ABCDEFG', 2, None) --> C D E F G``
58+:func:`imap`            func, p, q, ...                 func(p0, q0), func(p1, q1), ...                     ``imap(pow, (2,3,10), (5,2,3)) --> 32 9 1000``
59+:func:`starmap`         func, seq                       func(\*seq[0]), func(\*seq[1]), ...                 ``starmap(pow, [(2,5), (3,2), (10,3)]) --> 32 9 1000``
60+:func:`tee`             it, n                           it1, it2 , ... itn  splits one iterator into n
61+:func:`takewhile`       pred, seq                       seq[0], seq[1], until pred fails                    ``takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4``
62+:func:`izip`            p, q, ...                       (p[0], q[0]), (p[1], q[1]), ...                     ``izip('ABCD', 'xy') --> Ax By``
63+:func:`izip_longest`    p, q, ...                       (p[0], q[0]), (p[1], q[1]), ...                     ``izip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-``
64+====================    ============================    =================================================   =============================================================
48
n49-   The Standard ML Basis Library, `The Standard ML Basis Library
n66+**Combinatoric generators:**
50-   <http://www.standardml.org/Basis/>`_.
51
n52-   Haskell, A Purely Functional Language, `Definition of Haskell and the Standard
n68+==============================================   ====================       =============================================================
53-   Libraries <http://www.haskell.org/definition/>`_.
69+Iterator                                         Arguments                  Results
70+==============================================   ====================       =============================================================
71+:func:`product`                                  p, q, ... [repeat=1]       cartesian product, equivalent to a nested for-loop
72+:func:`permutations`                             p[, r]                     r-length tuples, all possible orderings, no repeated elements
73+:func:`combinations`                             p[, r]                     r-length tuples, in sorted order, no repeated elements
74+|
75+``product('ABCD', repeat=2)``                                               ``AA AB AC AD BA BB BC BD CA CB CC CD DA DB DC DD``
76+``permutations('ABCD', 2)``                                                 ``AB AC AD BA BC BD CA CB CD DA DB DC``
77+``combinations('ABCD', 2)``                                                 ``AB AC AD BC BD CD``
78+==============================================   ====================       =============================================================
54
55
56.. _itertools-functions:
57
58Itertool functions
59------------------
60
61The following module functions all construct and return iterators. Some provide
66.. function:: chain(*iterables)
67
68   Make an iterator that returns elements from the first iterable until it is
69   exhausted, then proceeds to the next iterable, until all of the iterables are
70   exhausted.  Used for treating consecutive sequences as a single sequence.
71   Equivalent to::
72
73      def chain(*iterables):
n99+          # chain('ABC', 'DEF') --> A B C D E F
74          for it in iterables:
75              for element in it:
76                  yield element
77
78
n105+.. function:: itertools.chain.from_iterable(iterable)
106+ 
107+   Alternate constructor for :func:`chain`.  Gets chained inputs from a
108+   single iterable argument that is evaluated lazily.  Equivalent to::
109+ 
110+      @classmethod
111+      def from_iterable(iterables):
112+          # chain.from_iterable(['ABC', 'DEF']) --> A B C D E F
113+          for it in iterables:
114+              for element in it:
115+                  yield element
116+ 
117+   .. versionadded:: 2.6
118+ 
119+ 
120+.. function:: combinations(iterable, r)
121+ 
122+   Return *r* length subsequences of elements from the input *iterable*.
123+ 
124+   Combinations are emitted in lexicographic sort order.  So, if the
125+   input *iterable* is sorted, the combination tuples will be produced
126+   in sorted order.
127+ 
128+   Elements are treated as unique based on their position, not on their
129+   value.  So if the input elements are unique, there will be no repeat
130+   values in each combination.
131+ 
132+   Equivalent to::
133+ 
134+        def combinations(iterable, r):
135+            # combinations('ABCD', 2) --> AB AC AD BC BD CD
136+            # combinations(range(4), 3) --> 012 013 023 123
137+            pool = tuple(iterable)
138+            n = len(pool)
139+            if r > n:
140+                return
141+            indices = range(r)
142+            yield tuple(pool[i] for i in indices)
143+            while True:
144+                for i in reversed(range(r)):
145+                    if indices[i] != i + n - r:
146+                        break
147+                else:
148+                    return
149+                indices[i] += 1
150+                for j in range(i+1, r):
151+                    indices[j] = indices[j-1] + 1
152+                yield tuple(pool[i] for i in indices)
153+ 
154+   The code for :func:`combinations` can be also expressed as a subsequence
155+   of :func:`permutations` after filtering entries where the elements are not
156+   in sorted order (according to their position in the input pool)::
157+ 
158+        def combinations(iterable, r):
159+            pool = tuple(iterable)
160+            n = len(pool)
161+            for indices in permutations(range(n), r):
162+                if sorted(indices) == list(indices):
163+                    yield tuple(pool[i] for i in indices)
164+ 
165+   The number of items returned is ``n! / r! / (n-r)!`` when ``0 <= r <= n``
166+   or zero when ``r > n``.
167+ 
168+   .. versionadded:: 2.6
169+ 
79.. function:: count([n])
80
81   Make an iterator that returns consecutive integers starting with *n*. If not
n82-   specified *n* defaults to zero.   Does not currently support python long
n173+   specified *n* defaults to zero.   Often used as an argument to :func:`imap` to
83-   integers.  Often used as an argument to :func:`imap` to generate consecutive
174+   generate consecutive data points. Also, used with :func:`izip` to add sequence
84-   data points. Also, used with :func:`izip` to add sequence numbers.  Equivalent
175+   numbers.  Equivalent to::
85-   to::
86
87      def count(n=0):
n178+          # count(10) --> 10 11 12 13 14 ...
88          while True:
89              yield n
90              n += 1
91
n92-   Note, :func:`count` does not check for overflow and will return negative numbers
93-   after exceeding ``sys.maxint``.  This behavior may change in the future.
94- 
95
96.. function:: cycle(iterable)
97
98   Make an iterator returning elements from the iterable and saving a copy of each.
99   When the iterable is exhausted, return elements from the saved copy.  Repeats
100   indefinitely.  Equivalent to::
101
102      def cycle(iterable):
n191+          # cycle('ABCD') --> A B C D A B C D A B C D ...
103          saved = []
104          for element in iterable:
105              yield element
106              saved.append(element)
107          while saved:
108              for element in saved:
109                    yield element
110
111   Note, this member of the toolkit may require significant auxiliary storage
112   (depending on the length of the iterable).
113
114
115.. function:: dropwhile(predicate, iterable)
116
117   Make an iterator that drops elements from the iterable as long as the predicate
118   is true; afterwards, returns every element.  Note, the iterator does not produce
n119-   *any* output until the predicate is true, so it may have a lengthy start-up
n208+   *any* output until the predicate first becomes false, so it may have a lengthy
120-   time.  Equivalent to::
209+   start-up time.  Equivalent to::
121
122      def dropwhile(predicate, iterable):
n212+          # dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 6 4 1
123          iterable = iter(iterable)
124          for x in iterable:
125              if not predicate(x):
126                  yield x
127                  break
128          for x in iterable:
129              yield x
130
132.. function:: groupby(iterable[, key])
133
134   Make an iterator that returns consecutive keys and groups from the *iterable*.
135   The *key* is a function computing a key value for each element.  If not
136   specified or is ``None``, *key* defaults to an identity function and returns
137   the element unchanged.  Generally, the iterable needs to already be sorted on
138   the same key function.
139
n230+   The operation of :func:`groupby` is similar to the ``uniq`` filter in Unix.  It
231+   generates a break or new group every time the value of the key function changes
232+   (which is why it is usually necessary to have sorted the data using the same key
233+   function).  That behavior differs from SQL's GROUP BY which aggregates common
234+   elements regardless of their input order.
235+ 
140   The returned group is itself an iterator that shares the underlying iterable
141   with :func:`groupby`.  Because the source is shared, when the :func:`groupby`
142   object is advanced, the previous group is no longer visible.  So, if that data
143   is needed later, it should be stored as a list::
144
145      groups = []
146      uniquekeys = []
n243+      data = sorted(data, key=keyfunc)
147      for k, g in groupby(data, keyfunc):
148          groups.append(list(g))      # Store group iterator as a list
149          uniquekeys.append(k)
150
151   :func:`groupby` is equivalent to::
152
153      class groupby(object):
n251+          # [k for k, g in groupby('AAAABBBCCDAABBB')] --> A B C D A B
252+          # [list(g) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC D
154          def __init__(self, iterable, key=None):
155              if key is None:
156                  key = lambda x: x
157              self.keyfunc = key
158              self.it = iter(iterable)
n159-              self.tgtkey = self.currkey = self.currvalue = xrange(0)
n258+              self.tgtkey = self.currkey = self.currvalue = object()
160          def __iter__(self):
161              return self
162          def next(self):
163              while self.currkey == self.tgtkey:
n164-                  self.currvalue = self.it.next() # Exit on StopIteration
n263+                  self.currvalue = next(self.it)    # Exit on StopIteration
165                  self.currkey = self.keyfunc(self.currvalue)
166              self.tgtkey = self.currkey
167              return (self.currkey, self._grouper(self.tgtkey))
168          def _grouper(self, tgtkey):
169              while self.currkey == tgtkey:
170                  yield self.currvalue
n171-                  self.currvalue = self.it.next() # Exit on StopIteration
n270+                  self.currvalue = next(self.it)    # Exit on StopIteration
172                  self.currkey = self.keyfunc(self.currvalue)
173
174   .. versionadded:: 2.4
175
176
177.. function:: ifilter(predicate, iterable)
178
179   Make an iterator that filters elements from iterable returning only those for
180   which the predicate is ``True``. If *predicate* is ``None``, return the items
181   that are true. Equivalent to::
182
183      def ifilter(predicate, iterable):
n283+          # ifilter(lambda x: x%2, range(10)) --> 1 3 5 7 9
184          if predicate is None:
185              predicate = bool
186          for x in iterable:
187              if predicate(x):
188                  yield x
189
190
191.. function:: ifilterfalse(predicate, iterable)
192
193   Make an iterator that filters elements from iterable returning only those for
194   which the predicate is ``False``. If *predicate* is ``None``, return the items
195   that are false. Equivalent to::
196
197      def ifilterfalse(predicate, iterable):
n298+          # ifilterfalse(lambda x: x%2, range(10)) --> 0 2 4 6 8
198          if predicate is None:
199              predicate = bool
200          for x in iterable:
201              if not predicate(x):
202                  yield x
203
204
205.. function:: imap(function, *iterables)
208   iterables.  If *function* is set to ``None``, then :func:`imap` returns the
209   arguments as a tuple.  Like :func:`map` but stops when the shortest iterable is
210   exhausted instead of filling in ``None`` for shorter iterables.  The reason for
211   the difference is that infinite iterator arguments are typically an error for
212   :func:`map` (because the output is fully evaluated) but represent a common and
213   useful way of supplying arguments to :func:`imap`. Equivalent to::
214
215      def imap(function, *iterables):
n317+          # imap(pow, (2,3,10), (5,2,3)) --> 32 9 1000
216          iterables = map(iter, iterables)
217          while True:
n218-              args = [i.next() for i in iterables]
n320+              args = [next(it) for it in iterables]
219              if function is None:
220                  yield tuple(args)
221              else:
222                  yield function(*args)
223
224
225.. function:: islice(iterable, [start,] stop [, step])
226
230   one which results in items being skipped.  If *stop* is ``None``, then iteration
231   continues until the iterator is exhausted, if at all; otherwise, it stops at the
232   specified position.  Unlike regular slicing, :func:`islice` does not support
233   negative values for *start*, *stop*, or *step*.  Can be used to extract related
234   fields from data where the internal structure has been flattened (for example, a
235   multi-line report may list a name field on every third line).  Equivalent to::
236
237      def islice(iterable, *args):
n340+          # islice('ABCDEFG', 2) --> A B
341+          # islice('ABCDEFG', 2, 4) --> C D
342+          # islice('ABCDEFG', 2, None) --> C D E F G
343+          # islice('ABCDEFG', 0, None, 2) --> A C E G
238          s = slice(*args)
239          it = iter(xrange(s.start or 0, s.stop or sys.maxint, s.step or 1))
n240-          nexti = it.next()
n346+          nexti = next(it)
241          for i, element in enumerate(iterable):
242              if i == nexti:
243                  yield element
n244-                  nexti = it.next()          
n350+                  nexti = next(it)
245
246   If *start* is ``None``, then iteration starts at zero. If *step* is ``None``,
247   then the step defaults to one.
248
249   .. versionchanged:: 2.5
250      accept ``None`` values for default *start* and *step*.
251
252
253.. function:: izip(*iterables)
254
255   Make an iterator that aggregates elements from each of the iterables. Like
256   :func:`zip` except that it returns an iterator instead of a list.  Used for
257   lock-step iteration over several iterables at a time.  Equivalent to::
258
259      def izip(*iterables):
n366+          # izip('ABCD', 'xy') --> Ax By
260          iterables = map(iter, iterables)
261          while iterables:
n262-              result = [it.next() for it in iterables]
n369+              yield yield tuple(map(next, iterables))
263-              yield tuple(result)
264
265   .. versionchanged:: 2.4
266      When no iterables are specified, returns a zero length iterator instead of
267      raising a :exc:`TypeError` exception.
268
n269-   Note, the left-to-right evaluation order of the iterables is guaranteed. This
n375+   The left-to-right evaluation order of the iterables is guaranteed. This
270-   makes possible an idiom for clustering a data series into n-length groups using
376+   makes possible an idiom for clustering a data series into n-length groups
271-   ``izip(*[iter(s)]*n)``.  For data that doesn't fit n-length groups exactly, the
377+   using ``izip(*[iter(s)]*n)``.
272-   last tuple can be pre-padded with fill values using ``izip(*[chain(s,
273-   [None]*(n-1))]*n)``.
274
n275-   Note, when :func:`izip` is used with unequal length inputs, subsequent iteration
n379+   :func:`izip` should only be used with unequal length inputs when you don't
276-   over the longer iterables cannot reliably be continued after :func:`izip`
380+   care about trailing, unmatched values from the longer iterables.  If those
277-   terminates.  Potentially, up to one entry will be missing from each of the left-
381+   values are important, use :func:`izip_longest` instead.
278-   over iterables. This occurs because a value is fetched from each iterator in-
279-   turn, but the process ends when one of the iterators terminates.  This leaves
280-   the last fetched values in limbo (they cannot be returned in a final, incomplete
281-   tuple and they are cannot be pushed back into the iterator for retrieval with
282-   ``it.next()``).  In general, :func:`izip` should only be used with unequal
283-   length inputs when you don't care about trailing, unmatched values from the
284-   longer iterables.
285
n383+ 
384+.. function:: izip_longest(*iterables[, fillvalue])
385+ 
386+   Make an iterator that aggregates elements from each of the iterables. If the
387+   iterables are of uneven length, missing values are filled-in with *fillvalue*.
388+   Iteration continues until the longest iterable is exhausted.  Equivalent to::
389+ 
390+      def izip_longest(*args, **kwds):
391+          # izip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-
392+          fillvalue = kwds.get('fillvalue')
393+          def sentinel(counter = ([fillvalue]*(len(args)-1)).pop):
394+              yield counter()         # yields the fillvalue, or raises IndexError
395+          fillers = repeat(fillvalue)
396+          iters = [chain(it, sentinel(), fillers) for it in args]
397+          try:
398+              for tup in izip(*iters):
399+                  yield tup
400+          except IndexError:
401+              pass
402+ 
403+   If one of the iterables is potentially infinite, then the
404+   :func:`izip_longest` function should be wrapped with something that limits
405+   the number of calls (for example :func:`islice` or :func:`takewhile`).  If
406+   not specified, *fillvalue* defaults to ``None``.
407+ 
408+   .. versionadded:: 2.6
409+ 
410+.. function:: permutations(iterable[, r])
411+ 
412+   Return successive *r* length permutations of elements in the *iterable*.
413+ 
414+   If *r* is not specified or is ``None``, then *r* defaults to the length
415+   of the *iterable* and all possible full-length permutations
416+   are generated.
417+ 
418+   Permutations are emitted in lexicographic sort order.  So, if the
419+   input *iterable* is sorted, the permutation tuples will be produced
420+   in sorted order.
421+ 
422+   Elements are treated as unique based on their position, not on their
423+   value.  So if the input elements are unique, there will be no repeat
424+   values in each permutation.
425+ 
426+   Equivalent to::
427+ 
428+        def permutations(iterable, r=None):
429+            # permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
430+            # permutations(range(3)) --> 012 021 102 120 201 210
431+            pool = tuple(iterable)
432+            n = len(pool)
433+            r = n if r is None else r
434+            if r > n:
435+                return
436+            indices = range(n)
437+            cycles = range(n, n-r, -1)
438+            yield tuple(pool[i] for i in indices[:r])
439+            while n:
440+                for i in reversed(range(r)):
441+                    cycles[i] -= 1
442+                    if cycles[i] == 0:
443+                        indices[i:] = indices[i+1:] + indices[i:i+1]
444+                        cycles[i] = n - i
445+                    else:
446+                        j = cycles[i]
447+                        indices[i], indices[-j] = indices[-j], indices[i]
448+                        yield tuple(pool[i] for i in indices[:r])
449+                        break
450+                else:
451+                    return
452+ 
453+   The code for :func:`permutations` can be also expressed as a subsequence of
454+   :func:`product`, filtered to exclude entries with repeated elements (those
455+   from the same position in the input pool)::
456+ 
457+        def permutations(iterable, r=None):
458+            pool = tuple(iterable)
459+            n = len(pool)
460+            r = n if r is None else r
461+            for indices in product(range(n), repeat=r):
462+                if len(set(indices)) == r:
463+                    yield tuple(pool[i] for i in indices)
464+ 
465+   The number of items returned is ``n! / (n-r)!`` when ``0 <= r <= n``
466+   or zero when ``r > n``.
467+ 
468+   .. versionadded:: 2.6
469+ 
470+.. function:: product(*iterables[, repeat])
471+ 
472+   Cartesian product of input iterables.
473+ 
474+   Equivalent to nested for-loops in a generator expression. For example,
475+   ``product(A, B)`` returns the same as ``((x,y) for x in A for y in B)``.
476+ 
477+   The nested loops cycle like an odometer with the rightmost element advancing
478+   on every iteration.  This pattern creates a lexicographic ordering so that if
479+   the input's iterables are sorted, the product tuples are emitted in sorted
480+   order.
481+ 
482+   To compute the product of an iterable with itself, specify the number of
483+   repetitions with the optional *repeat* keyword argument.  For example,
484+   ``product(A, repeat=4)`` means the same as ``product(A, A, A, A)``.
485+ 
486+   This function is equivalent to the following code, except that the
487+   actual implementation does not build up intermediate results in memory::
488+ 
489+       def product(*args, **kwds):
490+           # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
491+           # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
492+           pools = map(tuple, args) * kwds.get('repeat', 1)
493+           result = [[]]
494+           for pool in pools:
495+               result = [x+[y] for x in result for y in pool]
496+           for prod in result:
497+               yield tuple(prod)
498+ 
499+   .. versionadded:: 2.6
286
287.. function:: repeat(object[, times])
288
289   Make an iterator that returns *object* over and over again. Runs indefinitely
290   unless the *times* argument is specified. Used as argument to :func:`imap` for
n291-   invariant parameters to the called function.  Also used with :func:`izip` to
n505+   invariant function parameters.  Also used with :func:`izip` to create constant
292-   create an invariant part of a tuple record.  Equivalent to::
506+   fields in a tuple record.  Equivalent to::
293
294      def repeat(object, times=None):
n509+          # repeat(10, 3) --> 10 10 10
295          if times is None:
296              while True:
297                  yield object
298          else:
299              for i in xrange(times):
300                  yield object
301
302
303.. function:: starmap(function, iterable)
304
n305-   Make an iterator that computes the function using arguments tuples obtained from
n520+   Make an iterator that computes the function using arguments obtained from
306   the iterable.  Used instead of :func:`imap` when argument parameters are already
307   grouped in tuples from a single iterable (the data has been "pre-zipped").  The
308   difference between :func:`imap` and :func:`starmap` parallels the distinction
309   between ``function(a,b)`` and ``function(*c)``. Equivalent to::
310
311      def starmap(function, iterable):
n312-          iterable = iter(iterable)
n527+          # starmap(pow, [(2,5), (3,2), (10,3)]) --> 32 9 1000
313-          while True:
528+          for args in iterable:
314-              yield function(*iterable.next())
529+              yield function(*args)
315
n531+   .. versionchanged:: 2.6
532+      Previously, :func:`starmap` required the function arguments to be tuples.
533+      Now, any iterable is allowed.
316
317.. function:: takewhile(predicate, iterable)
318
319   Make an iterator that returns elements from the iterable as long as the
320   predicate is true.  Equivalent to::
321
322      def takewhile(predicate, iterable):
n541+          # takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4
323          for x in iterable:
324              if predicate(x):
325                  yield x
326              else:
327                  break
328
329
330.. function:: tee(iterable[, n=2])
331
n332-   Return *n* independent iterators from a single iterable. The case where ``n==2``
n551+   Return *n* independent iterators from a single iterable.  Equivalent to::
333-   is equivalent to::
334
n335-      def tee(iterable):
n553+        def tee(iterable, n=2):
336-          def gen(next, data={}, cnt=[0]):
337-              for i in count():
338-                  if i == cnt[0]:
339-                      item = data[i] = next()
340-                      cnt[0] += 1
341-                  else:
342-                      item = data.pop(i)
343-                  yield item
344-          it = iter(iterable)
554+            it = iter(iterable)
345-          return (gen(it.next), gen(it.next))
555+            deques = [collections.deque() for i in range(n)]
556+            def gen(mydeque):
557+                while True:
558+                    if not mydeque:             # when the local deque is empty
559+                        newval = next(it)       # fetch a new value and
560+                        for d in deques:        # load it to all the deques
561+                            d.append(newval)
562+                    yield mydeque.popleft()
563+            return tuple(gen(d) for d in deques)
346
n347-   Note, once :func:`tee` has made a split, the original *iterable* should not be
n565+   Once :func:`tee` has made a split, the original *iterable* should not be
348-   used anywhere else; otherwise, the *iterable* could get advanced without the tee
566+   used anywhere else; otherwise, the *iterable* could get advanced without
349-   objects being informed.
567+   the tee objects being informed.
350
n351-   Note, this member of the toolkit may require significant auxiliary storage
n569+   This itertool may require significant auxiliary storage (depending on how
352-   (depending on how much temporary data needs to be stored). In general, if one
570+   much temporary data needs to be stored). In general, if one iterator uses
353-   iterator is going to use most or all of the data before the other iterator, it
571+   most or all of the data before another iterator starts, it is faster to use
354-   is faster to use :func:`list` instead of :func:`tee`.
572+   :func:`list` instead of :func:`tee`.
355
356   .. versionadded:: 2.4
357
358
359.. _itertools-example:
360
361Examples
362--------
363
364The following examples show common uses for each tool and demonstrate ways they
n365-can be combined. ::
n583+can be combined.
366
n367-   >>> amounts = [120.15, 764.05, 823.14]
n585+.. doctest::
368-   >>> for checknum, amount in izip(count(1200), amounts):
369-   ...     print 'Check %d is for $%.2f' % (checknum, amount)
370-   ...
371-   Check 1200 is for $120.15
372-   Check 1201 is for $764.05
373-   Check 1202 is for $823.14
374
n375-   >>> import operator
376-   >>> for cube in imap(operator.pow, xrange(1,5), repeat(3)):
377-   ...    print cube
378-   ...
379-   1
380-   8
381-   27
382-   64
383- 
384-   >>> reportlines = ['EuroPython', 'Roster', '', 'alex', '', 'laura',
385-                     '', 'martin', '', 'walter', '', 'mark']
386-   >>> for name in islice(reportlines, 3, None, 2):
387-   ...    print name.title()
388-   ...
389-   Alex
390-   Laura
391-   Martin
392-   Walter
393-   Mark
394- 
395-   # Show a dictionary sorted and grouped by value
587+   >>> # Show a dictionary sorted and grouped by value
396   >>> from operator import itemgetter
397   >>> d = dict(a=1, b=2, c=1, d=2, e=1, f=2, g=3)
398   >>> di = sorted(d.iteritems(), key=itemgetter(1))
399   >>> for k, g in groupby(di, key=itemgetter(1)):
400   ...     print k, map(itemgetter(0), g)
401   ...
402   1 ['a', 'c', 'e']
403   2 ['b', 'd', 'f']
404   3 ['g']
405
n406-   # Find runs of consecutive numbers using groupby.  The key to the solution
n598+   >>> # Find runs of consecutive numbers using groupby.  The key to the solution
407-   # is differencing with a range so that consecutive numbers all appear in
599+   >>> # is differencing with a range so that consecutive numbers all appear in
408-   # same group.
600+   >>> # same group.
409   >>> data = [ 1,  4,5,6, 10, 15,16,17,18, 22, 25,26,27,28]
410   >>> for k, g in groupby(enumerate(data), lambda (i,x):i-x):
n411-   ...     print map(operator.itemgetter(1), g)
n603+   ...     print map(itemgetter(1), g)
412-   ... 
604+   ...
413   [1]
414   [4, 5, 6]
415   [10]
416   [15, 16, 17, 18]
417   [22]
418   [25, 26, 27, 28]
419
420
427This section shows recipes for creating an extended toolset using the existing
428itertools as building blocks.
429
430The extended tools offer the same high performance as the underlying toolset.
431The superior memory performance is kept by processing elements one at a time
432rather than bringing the whole iterable into memory all at once. Code volume is
433kept small by linking the tools together in a functional style which helps
434eliminate temporary variables.  High speed is retained by preferring
n435-"vectorized" building blocks over the use of for-loops and generators which
n627+"vectorized" building blocks over the use of for-loops and :term:`generator`\s
436-incur interpreter overhead. ::
628+which incur interpreter overhead.
437
n630+.. testcode::
631+ 
438-   def take(n, seq):
632+   def take(n, iterable):
633+       "Return first n items of the iterable as a list"
439-       return list(islice(seq, n))
634+       return list(islice(iterable, n))
440
n441-   def enumerate(iterable):
n636+   def enumerate(iterable, start=0):
442-       return izip(count(), iterable)
637+       return izip(count(start), iterable)
443
n444-   def tabulate(function):
n639+   def tabulate(function, start=0):
445       "Return function(0), function(1), ..."
n446-       return imap(function, count())
n641+       return imap(function, count(start))
447
n448-   def iteritems(mapping):
n643+   def consume(iterator, n):
449-       return izip(mapping.iterkeys(), mapping.itervalues())
644+       "Advance the iterator n-steps ahead. If n is none, consume entirely."
645+       collections.deque(islice(iterator, n), maxlen=0)
450
n451-   def nth(iterable, n):
n647+   def nth(iterable, n, default=None):
452-       "Returns the nth item"
648+       "Returns the nth item or a default value"
453-       return list(islice(iterable, n, n+1))
649+       return next(islice(iterable, n, None), default)
454
n455-   def all(seq, pred=None):
456-       "Returns True if pred(x) is true for every element in the iterable"
457-       for elem in ifilterfalse(pred, seq):
458-           return False
459-       return True
460- 
461-   def any(seq, pred=None):
462-       "Returns True if pred(x) is true for at least one element in the iterable"
463-       for elem in ifilter(pred, seq):
464-           return True
465-       return False
466- 
467-   def no(seq, pred=None):
468-       "Returns True if pred(x) is false for every element in the iterable"
469-       for elem in ifilter(pred, seq):
470-           return False
471-       return True
472- 
473-   def quantify(seq, pred=None):
651+   def quantify(iterable, pred=bool):
474-       "Count how many times the predicate is true in the sequence"
652+       "Count how many times the predicate is true"
475-       return sum(imap(pred, seq))
653+       return sum(imap(pred, iterable))
476
n477-   def padnone(seq):
n655+   def padnone(iterable):
478       """Returns the sequence elements and then returns None indefinitely.
479
480       Useful for emulating the behavior of the built-in map() function.
481       """
n482-       return chain(seq, repeat(None))
n660+       return chain(iterable, repeat(None))
483
n484-   def ncycles(seq, n):
n662+   def ncycles(iterable, n):
485       "Returns the sequence elements n times"
n486-       return chain(*repeat(seq, n))
n664+       return chain.from_iterable(repeat(iterable, n))
487
488   def dotproduct(vec1, vec2):
489       return sum(imap(operator.mul, vec1, vec2))
490
491   def flatten(listOfLists):
n492-       return list(chain(*listOfLists))
n670+       return list(chain.from_iterable(listOfLists))
493
494   def repeatfunc(func, times=None, *args):
495       """Repeat calls to func with specified arguments.
496
497       Example:  repeatfunc(random.random)
498       """
499       if times is None:
500           return starmap(func, repeat(args))
n501-       else:
502-           return starmap(func, repeat(args, times))
679+       return starmap(func, repeat(args, times))
503
504   def pairwise(iterable):
505       "s -> (s0,s1), (s1,s2), (s2, s3), ..."
506       a, b = tee(iterable)
n507-       try:
n684+       next(b, None)
508-           b.next()
509-       except StopIteration:
510-           pass
511       return izip(a, b)
512
n513-   def grouper(n, iterable, padvalue=None):
n687+   def grouper(n, iterable, fillvalue=None):
514-       "grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')"
688+       "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
515-       return izip(*[chain(iterable, repeat(padvalue, n-1))]*n)
689+       args = [iter(iterable)] * n
690+       return izip_longest(fillvalue=fillvalue, *args)
516
n692+   def roundrobin(*iterables):
693+       "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
694+       # Recipe credited to George Sakkis
695+       pending = len(iterables)
696+       nexts = cycle(iter(it).next for it in iterables)
697+       while pending:
698+           try:
699+               for next in nexts:
700+                   yield next()
701+           except StopIteration:
702+               pending -= 1
703+               nexts = cycle(islice(nexts, pending))
517
n705+   def powerset(iterable):
706+       "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
707+       s = list(iterable)
708+       return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
518
t710+   def compress(data, selectors):
711+       "compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F"
712+       return (d for d, s in izip(data, selectors) if s)
713+ 
714+   def combinations_with_replacement(iterable, r):
715+       "combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC"
716+       # number items returned:  (n+r-1)! / r! / (n-1)!
717+       pool = tuple(iterable)
718+       n = len(pool)
719+       if not n and r:
720+           return
721+       indices = [0] * r
722+       yield tuple(pool[i] for i in indices)
723+       while True:
724+           for i in reversed(range(r)):
725+               if indices[i] != n - 1:
726+                   break
727+           else:
728+               return
729+           indices[i:] = [indices[i] + 1] * (r - i)
730+           yield tuple(pool[i] for i in indices)
731+ 
732+   def powerset(iterable):
733+       "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
734+       s = list(iterable)
735+       return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
736+ 
737+   def unique_everseen(iterable, key=None):
738+       "List unique elements, preserving order. Remember all elements ever seen."
739+       # unique_everseen('AAAABBBCCDAABBB') --> A B C D
740+       # unique_everseen('ABBCcAD', str.lower) --> A B C D
741+       seen = set()
742+       seen_add = seen.add
743+       if key is None:
744+           for element in iterable:
745+               if element not in seen:
746+                   seen_add(element)
747+                   yield element
748+       else:
749+           for element in iterable:
750+               k = key(element)
751+               if k not in seen:
752+                   seen_add(k)
753+                   yield element
754+ 
755+   def unique_justseen(iterable, key=None):
756+       "List unique elements, preserving order. Remember only the element just seen."
757+       # unique_justseen('AAAABBBCCDAABBB') --> A B C D A B
758+       # unique_justseen('ABBCcAD', str.lower) --> A B C A D
759+       return imap(next, imap(itemgetter(1), groupby(iterable, key)))
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op