MOON
Server: Apache/2.2.31 (Unix) mod_ssl/2.2.31 OpenSSL/0.9.8e-fips-rhel5 mod_bwlimited/1.4
System: Linux csr818.wilogic.com 2.6.18-419.el5xen #1 SMP Fri Feb 24 22:50:37 UTC 2017 x86_64
User: digitals (531)
PHP: 5.4.45
Disabled: NONE
Upload Files
File: //usr/share/doc/python-docs-2.4.3/html/lib/itertools-functions.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<link rel="STYLESHEET" href="lib.css" type='text/css' />
<link rel="SHORTCUT ICON" href="../icons/pyfav.png" type="image/png" />
<link rel='start' href='../index.html' title='Python Documentation Index' />
<link rel="first" href="lib.html" title='Python Library Reference' />
<link rel='contents' href='contents.html' title="Contents" />
<link rel='index' href='genindex.html' title='Index' />
<link rel='last' href='about.html' title='About this document...' />
<link rel='help' href='about.html' title='About this document...' />
<link rel="next" href="itertools-example.html" />
<link rel="prev" href="module-itertools.html" />
<link rel="parent" href="module-itertools.html" />
<link rel="next" href="itertools-example.html" />
<meta name='aesop' content='information' />
<title>5.16.1 Itertool functions </title>
</head>
<body>
<DIV CLASS="navigation">
<div id='top-navigation-panel' xml:id='top-navigation-panel'>
<table align="center" width="100%" cellpadding="0" cellspacing="2">
<tr>
<td class='online-navigation'><a rel="prev" title="5.16 itertools  "
  href="module-itertools.html"><img src='../icons/previous.png'
  border='0' height='32'  alt='Previous Page' width='32' /></A></td>
<td class='online-navigation'><a rel="parent" title="5.16 itertools  "
  href="module-itertools.html"><img src='../icons/up.png'
  border='0' height='32'  alt='Up One Level' width='32' /></A></td>
<td class='online-navigation'><a rel="next" title="5.16.2 Examples"
  href="itertools-example.html"><img src='../icons/next.png'
  border='0' height='32'  alt='Next Page' width='32' /></A></td>
<td align="center" width="100%">Python Library Reference</td>
<td class='online-navigation'><a rel="contents" title="Table of Contents"
  href="contents.html"><img src='../icons/contents.png'
  border='0' height='32'  alt='Contents' width='32' /></A></td>
<td class='online-navigation'><a href="modindex.html" title="Module Index"><img src='../icons/modules.png'
  border='0' height='32'  alt='Module Index' width='32' /></a></td>
<td class='online-navigation'><a rel="index" title="Index"
  href="genindex.html"><img src='../icons/index.png'
  border='0' height='32'  alt='Index' width='32' /></A></td>
</tr></table>
<div class='online-navigation'>
<b class="navlabel">Previous:</b>
<a class="sectref" rel="prev" href="module-itertools.html">5.16 itertools  </A>
<b class="navlabel">Up:</b>
<a class="sectref" rel="parent" href="module-itertools.html">5.16 itertools  </A>
<b class="navlabel">Next:</b>
<a class="sectref" rel="next" href="itertools-example.html">5.16.2 Examples</A>
</div>
<hr /></div>
</DIV>
<!--End of Navigation Panel-->

<H2><A NAME="SECTION0071610000000000000000"></A><A NAME="itertools-functions"></A>
<BR>
5.16.1 Itertool functions 
</H2>

<P>
The following module functions all construct and return iterators.
Some provide streams of infinite length, so they should only be accessed
by functions or loops that truncate the stream.

<P>
<dl><dt><table cellpadding="0" cellspacing="0"><tr valign="baseline">
  <td><nobr><b><tt id='l2h-1383' xml:id='l2h-1383' class="function">chain</tt></b>(</nobr></td>
  <td><var>*iterables</var>)</td></tr></table></dt>
<dd>
  Make an iterator that returns elements from the first iterable until
  it is exhausted, then proceeds to the next iterable, until all of the
  iterables are exhausted.  Used for treating consecutive sequences as
  a single sequence.  Equivalent to:

<P>
<div class="verbatim"><pre>
     def chain(*iterables):
         for it in iterables:
             for element in it:
                 yield element
</pre></div>
</dl>

<P>
<dl><dt><table cellpadding="0" cellspacing="0"><tr valign="baseline">
  <td><nobr><b><tt id='l2h-1384' xml:id='l2h-1384' class="function">count</tt></b>(</nobr></td>
  <td><var></var><big>[</big><var>n</var><big>]</big><var></var>)</td></tr></table></dt>
<dd>
  Make an iterator that returns consecutive integers starting with <var>n</var>.
  If not specified <var>n</var> defaults to zero.  
  Does not currently support python long integers.  Often used as an
  argument to <tt class="function">imap()</tt> to generate consecutive data points.
  Also, used with <tt class="function">izip()</tt> to add sequence numbers.  Equivalent to:

<P>
<div class="verbatim"><pre>
     def count(n=0):
         while True:
             yield n
             n += 1
</pre></div>

<P>
Note, <tt class="function">count()</tt> does not check for overflow and will return
  negative numbers after exceeding <code>sys.maxint</code>.  This behavior
  may change in the future.
</dl>

<P>
<dl><dt><table cellpadding="0" cellspacing="0"><tr valign="baseline">
  <td><nobr><b><tt id='l2h-1385' xml:id='l2h-1385' class="function">cycle</tt></b>(</nobr></td>
  <td><var>iterable</var>)</td></tr></table></dt>
<dd>
  Make an iterator returning elements from the iterable and saving a
  copy of each.  When the iterable is exhausted, return elements from
  the saved copy.  Repeats indefinitely.  Equivalent to:

<P>
<div class="verbatim"><pre>
     def cycle(iterable):
         saved = []
         for element in iterable:
             yield element
             saved.append(element)
         while saved:
             for element in saved:
                   yield element
</pre></div>

<P>
Note, this member of the toolkit may require significant
  auxiliary storage (depending on the length of the iterable).
</dl>

<P>
<dl><dt><table cellpadding="0" cellspacing="0"><tr valign="baseline">
  <td><nobr><b><tt id='l2h-1386' xml:id='l2h-1386' class="function">dropwhile</tt></b>(</nobr></td>
  <td><var>predicate, iterable</var>)</td></tr></table></dt>
<dd>
  Make an iterator that drops elements from the iterable as long as
  the predicate is true; afterwards, returns every element.  Note,
  the iterator does not produce <em>any</em> output until the predicate
  is true, so it may have a lengthy start-up time.  Equivalent to:

<P>
<div class="verbatim"><pre>
     def dropwhile(predicate, iterable):
         iterable = iter(iterable)
         for x in iterable:
             if not predicate(x):
                 yield x
                 break
         for x in iterable:
             yield x
</pre></div>
</dl>

<P>
<dl><dt><table cellpadding="0" cellspacing="0"><tr valign="baseline">
  <td><nobr><b><tt id='l2h-1387' xml:id='l2h-1387' class="function">groupby</tt></b>(</nobr></td>
  <td><var>iterable</var><big>[</big><var>, key</var><big>]</big><var></var>)</td></tr></table></dt>
<dd>
  Make an iterator that returns consecutive keys and groups from the
  <var>iterable</var>. The <var>key</var> is a function computing a key value for each
  element.  If not specified or is <code>None</code>, <var>key</var> defaults to an
  identity function and returns  the element unchanged.  Generally, the
  iterable needs to already be sorted on the same key function.

<P>
The returned group is itself an iterator that shares the underlying
  iterable with <tt class="function">groupby()</tt>.  Because the source is shared, when
  the <tt class="function">groupby</tt> object is advanced, the previous group is no
  longer visible.  So, if that data is needed later, it should be stored
  as a list:

<P>
<div class="verbatim"><pre>
    groups = []
    uniquekeys = []
    for k, g in groupby(data, keyfunc):
        groups.append(list(g))      # Store group iterator as a list
        uniquekeys.append(k)
</pre></div>

<P>
<tt class="function">groupby()</tt> is equivalent to:

<P>
<div class="verbatim"><pre>
    class groupby(object):
        def __init__(self, iterable, key=None):
            if key is None:
                key = lambda x: x
            self.keyfunc = key
            self.it = iter(iterable)
            self.tgtkey = self.currkey = self.currvalue = xrange(0)
        def __iter__(self):
            return self
        def next(self):
            while self.currkey == self.tgtkey:
                self.currvalue = self.it.next() # Exit on StopIteration
                self.currkey = self.keyfunc(self.currvalue)
            self.tgtkey = self.currkey
            return (self.currkey, self._grouper(self.tgtkey))
        def _grouper(self, tgtkey):
            while self.currkey == tgtkey:
                yield self.currvalue
                self.currvalue = self.it.next() # Exit on StopIteration
                self.currkey = self.keyfunc(self.currvalue)
</pre></div>
  
<span class="versionnote">New in version 2.4.</span>

</dl>

<P>
<dl><dt><table cellpadding="0" cellspacing="0"><tr valign="baseline">
  <td><nobr><b><tt id='l2h-1388' xml:id='l2h-1388' class="function">ifilter</tt></b>(</nobr></td>
  <td><var>predicate, iterable</var>)</td></tr></table></dt>
<dd>
  Make an iterator that filters elements from iterable returning only
  those for which the predicate is <code>True</code>.
  If <var>predicate</var> is <code>None</code>, return the items that are true.
  Equivalent to:

<P>
<div class="verbatim"><pre>
     def ifilter(predicate, iterable):
         if predicate is None:
             predicate = bool
         for x in iterable:
             if predicate(x):
                 yield x
</pre></div>
</dl>

<P>
<dl><dt><table cellpadding="0" cellspacing="0"><tr valign="baseline">
  <td><nobr><b><tt id='l2h-1389' xml:id='l2h-1389' class="function">ifilterfalse</tt></b>(</nobr></td>
  <td><var>predicate, iterable</var>)</td></tr></table></dt>
<dd>
  Make an iterator that filters elements from iterable returning only
  those for which the predicate is <code>False</code>.
  If <var>predicate</var> is <code>None</code>, return the items that are false.
  Equivalent to:

<P>
<div class="verbatim"><pre>
     def ifilterfalse(predicate, iterable):
         if predicate is None:
             predicate = bool
         for x in iterable:
             if not predicate(x):
                 yield x
</pre></div>
</dl>

<P>
<dl><dt><table cellpadding="0" cellspacing="0"><tr valign="baseline">
  <td><nobr><b><tt id='l2h-1390' xml:id='l2h-1390' class="function">imap</tt></b>(</nobr></td>
  <td><var>function, *iterables</var>)</td></tr></table></dt>
<dd>
  Make an iterator that computes the function using arguments from
  each of the iterables.  If <var>function</var> is set to <code>None</code>, then
  <tt class="function">imap()</tt> returns the arguments as a tuple.  Like
  <tt class="function">map()</tt> but stops when the shortest iterable is exhausted
  instead of filling in <code>None</code> for shorter iterables.  The reason
  for the difference is that infinite iterator arguments are typically
  an error for <tt class="function">map()</tt> (because the output is fully evaluated)
  but represent a common and useful way of supplying arguments to
  <tt class="function">imap()</tt>.
  Equivalent to:

<P>
<div class="verbatim"><pre>
     def imap(function, *iterables):
         iterables = map(iter, iterables)
         while True:
             args = [i.next() for i in iterables]
             if function is None:
                 yield tuple(args)
             else:
                 yield function(*args)
</pre></div>
</dl>

<P>
<dl><dt><table cellpadding="0" cellspacing="0"><tr valign="baseline">
  <td><nobr><b><tt id='l2h-1391' xml:id='l2h-1391' class="function">islice</tt></b>(</nobr></td>
  <td><var>iterable, </var><big>[</big><var>start,</var><big>]</big><var> stop </var><big>[</big><var>, step</var><big>]</big><var></var>)</td></tr></table></dt>
<dd>
  Make an iterator that returns selected elements from the iterable.
  If <var>start</var> is non-zero, then elements from the iterable are skipped
  until start is reached.  Afterward, elements are returned consecutively
  unless <var>step</var> is set higher than one which results in items being
  skipped.  If <var>stop</var> is <code>None</code>, then iteration continues until
  the iterator is exhausted, if at all; otherwise, it stops at the specified
  position.  Unlike regular slicing,
  <tt class="function">islice()</tt> does not support negative values for <var>start</var>,
  <var>stop</var>, or <var>step</var>.  Can be used to extract related fields
  from data where the internal structure has been flattened (for
  example, a multi-line report may list a name field on every
  third line).  Equivalent to:

<P>
<div class="verbatim"><pre>
     def islice(iterable, *args):
         s = slice(*args)
         it = iter(xrange(s.start or 0, s.stop or sys.maxint, s.step or 1))
         nexti = it.next()
         for i, element in enumerate(iterable):
             if i == nexti:
                 yield element
                 nexti = it.next()
</pre></div>
</dl>

<P>
<dl><dt><table cellpadding="0" cellspacing="0"><tr valign="baseline">
  <td><nobr><b><tt id='l2h-1392' xml:id='l2h-1392' class="function">izip</tt></b>(</nobr></td>
  <td><var>*iterables</var>)</td></tr></table></dt>
<dd>
  Make an iterator that aggregates elements from each of the iterables.
  Like <tt class="function">zip()</tt> except that it returns an iterator instead of
  a list.  Used for lock-step iteration over several iterables at a
  time.  Equivalent to:

<P>
<div class="verbatim"><pre>
     def izip(*iterables):
         iterables = map(iter, iterables)
         while iterables:
             result = [it.next() for it in iterables]
             yield tuple(result)
</pre></div>

<P>

<span class="versionnote">Changed in version 2.4:
When no iterables are specified, returns a zero length
                  iterator instead of raising a TypeError exception.</span>

<P>
Note, the left-to-right evaluation order of the iterables is guaranteed.
  This makes possible an idiom for clustering a data series into n-length
  groups using "<tt class="samp">izip(*[iter(s)]*n)</tt>".  For data that doesn't fit
  n-length groups exactly, the last tuple can be pre-padded with fill
  values using "<tt class="samp">izip(*[chain(s, [None]*(n-1))]*n)</tt>".

<P>
Note, when <tt class="function">izip()</tt> is used with unequal length inputs, subsequent
  iteration over the longer iterables cannot reliably be continued after
  <tt class="function">izip()</tt> terminates.  Potentially, up to one entry will be missing
  from each of the left-over iterables. This occurs because a value is fetched
  from each iterator in-turn, but the process ends when one of the iterators
  terminates.  This leaves the last fetched values in limbo (they cannot be
  returned in a final, incomplete tuple and they are cannot be pushed back
  into the iterator for retrieval with <code>it.next()</code>).  In general,
  <tt class="function">izip()</tt> should only be used with unequal length inputs when you
  don't care about trailing, unmatched values from the longer iterables.
</dl>

<P>
<dl><dt><table cellpadding="0" cellspacing="0"><tr valign="baseline">
  <td><nobr><b><tt id='l2h-1393' xml:id='l2h-1393' class="function">repeat</tt></b>(</nobr></td>
  <td><var>object</var><big>[</big><var>, times</var><big>]</big><var></var>)</td></tr></table></dt>
<dd>
  Make an iterator that returns <var>object</var> over and over again.
  Runs indefinitely unless the <var>times</var> argument is specified.
  Used as argument to <tt class="function">imap()</tt> for invariant parameters
  to the called function.  Also used with <tt class="function">izip()</tt> to create
  an invariant part of a tuple record.  Equivalent to:

<P>
<div class="verbatim"><pre>
     def repeat(object, times=None):
         if times is None:
             while True:
                 yield object
         else:
             for i in xrange(times):
                 yield object
</pre></div>
</dl>

<P>
<dl><dt><table cellpadding="0" cellspacing="0"><tr valign="baseline">
  <td><nobr><b><tt id='l2h-1394' xml:id='l2h-1394' class="function">starmap</tt></b>(</nobr></td>
  <td><var>function, iterable</var>)</td></tr></table></dt>
<dd>
  Make an iterator that computes the function using arguments tuples
  obtained from the iterable.  Used instead of <tt class="function">imap()</tt> when
  argument parameters are already grouped in tuples from a single iterable
  (the data has been ``pre-zipped'').  The difference between
  <tt class="function">imap()</tt> and <tt class="function">starmap()</tt> parallels the distinction
  between <code>function(a,b)</code> and <code>function(*c)</code>.
  Equivalent to:

<P>
<div class="verbatim"><pre>
     def starmap(function, iterable):
         iterable = iter(iterable)
         while True:
             yield function(*iterable.next())
</pre></div>
</dl>

<P>
<dl><dt><table cellpadding="0" cellspacing="0"><tr valign="baseline">
  <td><nobr><b><tt id='l2h-1395' xml:id='l2h-1395' class="function">takewhile</tt></b>(</nobr></td>
  <td><var>predicate, iterable</var>)</td></tr></table></dt>
<dd>
  Make an iterator that returns elements from the iterable as long as
  the predicate is true.  Equivalent to:

<P>
<div class="verbatim"><pre>
     def takewhile(predicate, iterable):
         for x in iterable:
             if predicate(x):
                 yield x
             else:
                 break
</pre></div>
</dl>

<P>
<dl><dt><table cellpadding="0" cellspacing="0"><tr valign="baseline">
  <td><nobr><b><tt id='l2h-1396' xml:id='l2h-1396' class="function">tee</tt></b>(</nobr></td>
  <td><var>iterable</var><big>[</big><var>, n=2</var><big>]</big><var></var>)</td></tr></table></dt>
<dd>
  Return <var>n</var> independent iterators from a single iterable.
  The case where <code>n==2</code> is equivalent to:

<P>
<div class="verbatim"><pre>
     def tee(iterable):
         def gen(next, data={}, cnt=[0]):
             for i in count():
                 if i == cnt[0]:
                     item = data[i] = next()
                     cnt[0] += 1
                 else:
                     item = data.pop(i)
                 yield item
         it = iter(iterable)
         return (gen(it.next), gen(it.next))
</pre></div>

<P>
Note, once <tt class="function">tee()</tt> has made a split, the original <var>iterable</var>
  should not be used anywhere else; otherwise, the <var>iterable</var> could get
  advanced without the tee objects being informed.

<P>
Note, this member of the toolkit may require significant auxiliary
  storage (depending on how much temporary data needs to be stored).
  In general, if one iterator is going to use most or all of the data before
  the other iterator, it is faster to use <tt class="function">list()</tt> instead of
  <tt class="function">tee()</tt>.
  
<span class="versionnote">New in version 2.4.</span>

</dl>

<P>

<DIV CLASS="navigation">
<div class='online-navigation'>
<p></p><hr />
<table align="center" width="100%" cellpadding="0" cellspacing="2">
<tr>
<td class='online-navigation'><a rel="prev" title="5.16 itertools  "
  href="module-itertools.html"><img src='../icons/previous.png'
  border='0' height='32'  alt='Previous Page' width='32' /></A></td>
<td class='online-navigation'><a rel="parent" title="5.16 itertools  "
  href="module-itertools.html"><img src='../icons/up.png'
  border='0' height='32'  alt='Up One Level' width='32' /></A></td>
<td class='online-navigation'><a rel="next" title="5.16.2 Examples"
  href="itertools-example.html"><img src='../icons/next.png'
  border='0' height='32'  alt='Next Page' width='32' /></A></td>
<td align="center" width="100%">Python Library Reference</td>
<td class='online-navigation'><a rel="contents" title="Table of Contents"
  href="contents.html"><img src='../icons/contents.png'
  border='0' height='32'  alt='Contents' width='32' /></A></td>
<td class='online-navigation'><a href="modindex.html" title="Module Index"><img src='../icons/modules.png'
  border='0' height='32'  alt='Module Index' width='32' /></a></td>
<td class='online-navigation'><a rel="index" title="Index"
  href="genindex.html"><img src='../icons/index.png'
  border='0' height='32'  alt='Index' width='32' /></A></td>
</tr></table>
<div class='online-navigation'>
<b class="navlabel">Previous:</b>
<a class="sectref" rel="prev" href="module-itertools.html">5.16 itertools  </A>
<b class="navlabel">Up:</b>
<a class="sectref" rel="parent" href="module-itertools.html">5.16 itertools  </A>
<b class="navlabel">Next:</b>
<a class="sectref" rel="next" href="itertools-example.html">5.16.2 Examples</A>
</div>
</div>
<hr />
<span class="release-info">Release 2.4.3, documentation updated on 29 March 2006.</span>
</DIV>
<!--End of Navigation Panel-->
<ADDRESS>
See <i><a href="about.html">About this document...</a></i> for information on suggesting changes.
</ADDRESS>
</BODY>
</HTML>