title: Python execute code only if for loop did not begin iteration (with generator)?
body: <p>The <code>else</code> block in a <code>for</code>/<code>else</code> clause gets executed if the iteration finishes but is not interrupted by <code>break</code>, <a href="http://docs.python.org/2/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops" rel="noreferrer">so I read</a>.</p>
  
  <p>Is there a language construct which would let me write something which executes only if the <code>for</code> loop did not begin iteration? If I was using a <code>tuple</code> or <code>list</code>, I would do something like this:</p>
  
  <pre><code>if seq:
      for x in seq:
           # something
  else:
      # something else
  </code></pre>
  
  <p>But when I use a generator, I don't get the behavior I want:</p>
  
  <pre><code>&gt;&gt;&gt; g = (x for x in range(2))
  &gt;&gt;&gt; for x in g:
  ...     print x
  ... else:
  ...     print "done"
  ... 
  0
  1
  done    # I don't want "done" here
  &gt;&gt;&gt; g = (x for x in range(2) if x &gt; 1)
  &gt;&gt;&gt; if g:
  ...     for x in g:
  ...         print x
  ... else:
  ...     print "done"
  ... 
  &gt;&gt;&gt;     # I was expecting "done" here
  </code></pre>
  
  <p>How can I do this without exhausting creating a <code>tuple</code> or a <code>list</code> from the generator, while also using a <code>for</code> loop? I could use <code>next()</code> in a <code>while</code> loop and try to catch <code>StopIteration</code>, but I'd like to see if there's a nice way to do it with <code>for</code>.</p>