title: How to limit the size of a comprehension?
body: <p>I have a <code>list</code> and want to build (via a comprehension) another list. I would like this new list to be limited in size, via a condition</p>
  
  <p>The following code will fail:</p>
  
  <pre><code>a = [1, 2, 1, 2, 1, 2]
  b = [i for i in a if i == 1 and len(b) &lt; 3]
  </code></pre>
  
  <p>with</p>
  
  <pre><code>Traceback (most recent call last):
    File "compr.py", line 2, in &lt;module&gt;
      b = [i for i in a if i == 1 and len(b) &lt; 3]
    File "compr.py", line 2, in &lt;listcomp&gt;
      b = [i for i in a if i == 1 and len(b) &lt; 3]
  NameError: name 'b' is not defined
  </code></pre>
  
  <p>because <code>b</code> is not defined <strong>yet</strong> at the time the comprehension is built.</p>
  
  <p><strong>Is there a way to limit the size of the new list at build time?</strong></p>
  
  <p>Note: I could break the comprehension into a <code>for</code> loop with the proper <code>break</code> when a counter is reached but I would like to know if there is a mechanism which uses a comprehension.</p>