On 23 November 2017 at 15:33, Stephen J. Turnbull <turnbull.stephen.fw@u.tsukuba.ac.jp> wrote:
However, my model of comprehensions is exactly a for loop that appends
to an empty list repeatedly, but doesn't leak iteration variables.

Not since Python 3.0. Instead, they create a nested function, the same way generator expressions do (which is why the name resolution semantics are now identical between the two cases).

The differences in structure between the four cases (genexp, list/set/dict comprehensions) then relate mainly to what the innermost loop does:

    result.append(expr) # list comp
    result.add(expr) # set comp
    result[k] = v # dict comp
    yield expr # genexp

Thus, when the expression itself is a yield expression, you get:

    result.append(yield expr) # list comp
    result.add(yield expr) # set comp
    result[k] = (yield v) # dict comp
    yield (yield expr) # genexp

Cheers,
Nick.

--
Nick Coghlan   |   ncoghlan@gmail.com   |   Brisbane, Australia