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>Don't be fooled by the comma in <code>c, b</code>. In Python, commas -- not parentheses -- are what defines a tuple. Your code is equivalent to <code>[x for x in (b for (c, b) in a)]</code>, which iterates through the elements of <code>a</code>, assigning <code>c</code> to the first element of each two-element list in <code>a</code> and <code>b</code> to the second, and then assigning <code>b</code> to <code>x</code>. If <code>a</code> had an element that was not a two-element iterable, you would get a <code>ValueError</code>.</p>

python python-2.7