itertools.groupby function seems inconsistent
<p>I'm having trouble understanding exactly what it is that this function does because of I guess, the programming magic around its use?</p>

<p>It seems to me like it returns a list of keys (unique letters in a string) paired with iterators, that reference a list of the number of each of those letters in the original string, but sometimes it seems like this is not the case.</p>

<p>For example:</p>

<pre><code>import itertools

x = list(itertools.groupby("AAABBB"))
print x
</code></pre>

<p>which prints:</p>

<pre><code>[('A', &lt;itertools._grouper object at 0x101a0b050), 
 ('B', &lt;itertools._grouper object at 0x101a0b090)]
</code></pre>

<p>This seems correct, we have our unique keys paired with iterators. But when I run:</p>

<pre><code>print list(x[0][1])
</code></pre>

<p>I get:</p>

<pre><code>[]
</code></pre>

<p>and when I run</p>

<pre><code>for k, g in x:
    print k + ' - ' + g
</code></pre>

<p>I get:</p>

<pre><code>B - &lt;itertools._grouper object at 0x1007eedd5&gt;
</code></pre>

<p>It ignores the first element. This seems counter-intuitive, because if I just change the syntax a little bit:</p>

<pre><code>[list(g) for k, g in itertools.groupby("AAABBB")]
</code></pre>

<p>I get:</p>

<pre><code>[["A", "A", "A"], ["B", "B", "B"]]
</code></pre>

<p>which is right, and aligns with what I think this function should be doing.</p>

<p>However, if I once again change the syntax just a bit:</p>

<pre><code>[list(thing) for thing in [g for k, g in itertools.groupby(string)]]
</code></pre>

<p>I get back:</p>

<pre><code>[[], ['B']]
</code></pre>

<p>These two list comprehensions should be directly equivalent, but they return different results.</p>

<p>What is going on? Insight would be extremely appreciated.</p>

<p>The docs already explain why your listcomps aren't equivalent:</p>

<blockquote>
  <p>The returned group is itself an iterator that shares the underlying iterable with groupby(). Because the source is shared, when the groupby() object is advanced, the previous group is no longer visible. So, if that data is needed later, it should be stored as a list</p>
</blockquote>

<p>Your</p>

<pre><code>[list(g) for k, g in itertools.groupby("AAABBB")]
</code></pre>

<p><em>does</em> use each group before <code>groupby()</code> advances, so it works.</p>

<p>Your</p>

<pre><code>[list(thing) for thing in [g for k, g in itertools.groupby(string)]]
</code></pre>

<p>doesn't use any group until after all groups have been generated.  Not at all the same, and for the reason the quoted docs explained.</p>

python group-by list-comprehension itertools