Is it safe and pythonic to consume the iterator in the body of a for loop?
<p>Is it safe in Python to do something like this (say, in a parser)?</p>

<pre><code>iterator = iter(some_iterable)
for x in iterator:
    # do stuff with x
    if some_condition(x):
        y = next(iterator)
        # do stuff with y
</code></pre>

<p>I've tested in Python 2 and 3 and it does what I expect, but I wonder whether it's really safe and whether it's idiomatic. The above code should be equivalent to the following rather more verbose alternative:</p>

<pre><code>iterator = iter(some_iterable)
while True:
    try:
        x = next(iterator)
    except StopIteration:
        break
    # do stuff with x
    if some_condition(x):
        y = next(iterator)
        # do stuff with y
</code></pre>

<p>Basically it's always better to keep track of your exceptions and handle them properly. But regarding the difference between the <code>while</code> and <code>for</code> loops in this case when you are calling a <code>next()</code> function within a <code>while</code> loop it's always possible to raise an StopIteration exception, but when you are using a <code>for</code> loop based on the number of <code>next()</code> calls and your iteration it may be different.</p>

<p>For example in this case for even number of iteration it doesn't raise an exception but for odds it does. And the reason is that in even iteration numbers your next is always one item in front of the for loop, while for odds it's not like so.</p>

<pre><code>In [1]: it = iter(range(4))

In [2]: for x in it:
   ...:     print(x)
   ...:     next(it)
   ...:     
0
2

In [3]: it = iter(range(3))

In [4]: for x in it:
            print(x)
            next(it)
   ...:     
0
2
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
&lt;ipython-input-4-1b3db7079e29&gt; in &lt;module&gt;()
      1 for x in it:
      2             print(x)
----&gt; 3             next(it)
      4 

StopIteration: 
</code></pre>

python