Alejandro Wainzinger Alejandro Wainzinger - 1 year ago 80
Python Question

How does this for, in generator work in Python 2.7.x

I'm aware of the

for x in list
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
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?

$ 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.
>>> a = [[1,2],[3,4],[5,6]]
>>> (b for c, b in a)
<generator object <genexpr> at 0x1071abaa0>
>>> [x for x in (b for c, b in a)]
[2, 4, 6]

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

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download