[Python-Dev] Iteration variables and list comprehensions (original) (raw)

Fred L. Drake, Jr. fdrake@acm.org
Wed, 30 May 2001 10:03:13 -0400 (EDT)


David Beazley writes:

Maybe everyone else views list comprehensions as a series of statements (the syntactic sugar for nested for-loop idea). However,

I certainly don't. I know that that was used as part of the design consideration, but it's not at all clear to me that this is desirable. If I see code like this:

    x = 42
    L = [x**2 for x in range(2000)]
    print x

I think it should map to something like this from C++:

    int x = 42;
    int L[2000];

    for (int x = 0; x < 2000; ++x) {
        L[x] = x * x;
    }
    printf("%d\n", x);

i.e., both should print "42\n" on standard output.

Tim sez:

I'm not sure it's worth losing the exact correspondence with nested loops; or that it's not worth it either. Note that "the iterator variables" needn't be bare names:

class x: ... pass ... [1 for x.i in range(3)] [1, 1, 1] x.i 2

David:

Hmmm. I didn't realize that you could even do this. Yes, this would definitely present a problem. However, if list comprehensions were

I didn't realize this either. I'm quite surprised by it, in fact, though I understand (I think) why it works that way. But was this intentional? It seems like pure evil to me! I'd only expect it to support bare names and sequence unpacking (with only bare names at the "edge" of all nested unpackings).

-Fred

-- Fred L. Drake, Jr. PythonLabs at Digital Creations