Why does list(next(iter(())) for _ in range(1)) == []?
<p>Why does <code>list(next(iter(())) for _ in range(1))</code> return an empty list rather than raising <code>StopIteration</code>?</p>

<pre><code>&gt;&gt;&gt; next(iter(()))
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
StopIteration
&gt;&gt;&gt; [next(iter(())) for _ in range(1)]
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
StopIteration
&gt;&gt;&gt; list(next(iter(())) for _ in range(1))  # ?!
[]
</code></pre>

<p>The same thing happens with a custom function that explicitly raises <code>StopIteration</code>:</p>

<pre><code>&gt;&gt;&gt; def x():
...     raise StopIteration
... 
&gt;&gt;&gt; x()
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
  File "&lt;stdin&gt;", line 2, in x
StopIteration
&gt;&gt;&gt; [x() for _ in range(1)]
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
  File "&lt;stdin&gt;", line 2, in x
StopIteration
&gt;&gt;&gt; list(x() for _ in range(1))  # ?!
[]
</code></pre>

<p>assuming all goes well, the generator comprehension <code>x() for _ in range(1)</code> should raise <code>StopIteration</code> when it is finished iterating over <code>range(1)</code> to indicate that there are no more items to pack into the list.</p>

<p>However because <code>x()</code> raises <code>StopIteration</code> it ends up exiting early meaning this behaviour is a bug in python that is being addressed with <a href="http://legacy.python.org/dev/peps/pep-0479/">PEP 479</a></p>

<p>In python 3.6 or using <code>from __future__ import generator_stop</code> in python 3.5 when a StopIteration propagates out farther it is converted into a <code>RuntimeError</code> so that <code>list</code> doesn't register it as the end of the comprehension. When this is in effect the error looks like this:</p>

<pre><code>Traceback (most recent call last):
  File "/Users/Tadhg/Documents/codes/test.py", line 6, in &lt;genexpr&gt;
    stuff = list(x() for _ in range(1))
  File "/Users/Tadhg/Documents/codes/test.py", line 4, in x
    raise StopIteration
StopIteration

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/Users/Tadhg/Documents/codes/test.py", line 6, in &lt;module&gt;
    stuff = list(x() for _ in range(1))
RuntimeError: generator raised StopIteration
</code></pre>

python