python: how to get list length in list generator expression?
<p>Maybe like this (just a pseudocode)  </p>

<pre><code>li = [1,2,3,4,5,6]  
a = [d for d in li if self.length&lt;3]  
print a  
[1,2]  
</code></pre>

<p>What is a pythonic way to do that thing?  </p>

<p>You can use <code>itertools.count()</code> to keep track of how many elements you have used:</p>

<pre><code>from itertools import count

li = [1,2,3,4,5,6]
c = count(1)    # initialize to 1
a = [d for d in li if next(c) &lt; 3]   # everytime you add an element 
print (a)                            # in the comprehension `c` is incremented
</code></pre>

<p>That keeps track of the elements added to the list, hence the length of the list which gives:</p>

<pre><code>[1, 2]
</code></pre>

<p>as expected with length 2.</p>

<p><strong>EDITED:</strong> More easier way, with <code>enumerate</code>:</p>

<pre><code>a = [d for idx, d in enumerate(li) if idx &lt; 2]
</code></pre>

python