How does this for, in generator work in Python 2.7.x
<p>I'm aware of the <code>for x in list</code> loop in Python, but I stumbled on a type of generator whose documentation I couldn't find. I found out that the example below only works if the lists inside the list <code>a</code> are of length 2, or it gives an unpacking error, so I suspect some kind of 2-tuple or dict-related unpacker may be at play. Can somebody explain to me how this generator syntax works?</p>

<pre><code>$ python                                                                                                                                            
Python 2.7.10 (default, Oct 23 2015, 19:19:21) 
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
&gt;&gt;&gt; a = [[1,2],[3,4],[5,6]]
&gt;&gt;&gt; (b for c, b in a)
&lt;generator object &lt;genexpr&gt; at 0x1071abaa0&gt;
&gt;&gt;&gt; [x for x in (b for c, b in a)]
[2, 4, 6]
</code></pre>

<p>I ran into it in a project that used this generator in a call to <code>min</code>. Originally I thought it was multiple args being passed in, but the syntax made no sense, and testing it individually revealed a generator.</p>

<p><a href="https://github.com/bigbighd604/Python/blob/master/graph/Ford-Fulkerson.py#L59" rel="nofollow">https://github.com/bigbighd604/Python/blob/master/graph/Ford-Fulkerson.py#L59</a></p>

<p>Starting from the inside, we are creating a generator expression from list a:</p>

<pre><code>a = [[1,2],[3,4],[5,6]]
</code></pre>

<p>So, Let us look at that one alone:</p>

<pre><code>(b for c, b in a)
</code></pre>

<p>So, if you look back at list <code>a</code>, we have a list of lists, where each sub-list is just two items. So, what is happening here with your generator expression, is that <code>c, b</code> are representing each of the unpacked values in your sub-list as a tuple. However, if you look at the expression, we are only taking <code>b</code>, which is why the result will end up being: </p>

<pre><code>2, 4, 6
</code></pre>

<p>Then moving outward, we are then just creating a list-comprehension from that generator expression:</p>

<pre><code>[x for x in (b for c, b in a)]
</code></pre>

<p>Ending in a list:</p>

<pre><code>[2, 4, 6]
</code></pre>

<p>Actually, if you are looking to get a list out of that expression, you can just do:</p>

<pre><code>list(b for c, b in a)
</code></pre>

python python-2.7