Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There is a fantastic package in Python called <a href="http://docs.python.org/library/itertools.html" rel="noreferrer"><code>itertools</code></a>.</p> <p>But before I get into that, it'd serve well to explain how the iteration protocol is implemented in Python. When you want to provide iteration over your container, you specify the <a href="http://docs.python.org/reference/datamodel.html#object.__iter__" rel="noreferrer"><code>__iter__()</code></a> class method that provides an <a href="http://docs.python.org/library/stdtypes.html#iterator-types" rel="noreferrer">iterator type</a>. <a href="http://effbot.org/zone/python-for-statement.htm" rel="noreferrer">"Understanding Python's 'for' statement"</a> is a nice article covering how the <code>for-in</code> statement actually works in Python and provides a nice overview on how the iterator types work.</p> <p>Take a look at the following:</p> <pre><code>&gt;&gt;&gt; sequence = [1, 2, 3, 4, 5] &gt;&gt;&gt; iterator = sequence.__iter__() &gt;&gt;&gt; iterator.next() 1 &gt;&gt;&gt; iterator.next() 2 &gt;&gt;&gt; for number in iterator: print number 3 4 5 </code></pre> <p>Now back to <code>itertools</code>. The package contains functions for various iteration purposes. If you ever need to do special sequencing, this is the first place to look into.</p> <p>At the bottom you can find the <a href="http://docs.python.org/library/itertools.html#recipes" rel="noreferrer">Recipes</a> section that contain <em>recipes for creating an extended toolset using the existing itertools as building blocks</em>.</p> <p>And there's an interesting function that does exactly what you need:</p> <pre><code>def consume(iterator, n): '''Advance the iterator n-steps ahead. If n is none, consume entirely.''' collections.deque(itertools.islice(iterator, n), maxlen=0) </code></pre> <p>Here's a quick, readable, example on how it works <em>(Python 2.5)</em>:</p> <pre><code>&gt;&gt;&gt; import itertools, collections &gt;&gt;&gt; def consume(iterator, n): collections.deque(itertools.islice(iterator, n)) &gt;&gt;&gt; iterator = range(1, 16).__iter__() &gt;&gt;&gt; for number in iterator: if (number == 5): # Disregard 6, 7, 8, 9 (5 doesn't get printed just as well) consume(iterator, 4) else: print number 1 2 3 4 10 11 12 13 14 15 </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload