[Tutor] list comprehensions isolate variables but for loops don't - is there a special usage?

eryksun eryksun at gmail.com
Wed Jun 5 09:59:14 CEST 2013


On Wed, Jun 5, 2013 at 3:35 AM, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
> To be honest I didn't realize that comprehensions (and I assume generators
> in general) created their own local namespace. But thinking about it, it
> seems logical since they are effectively functions in disguise... Whereas
> for loops are structures of the language just like if statements or while
> loops. They live in whichever context they are used.

3.x compiles comprehensions as functions. 2.x compiles list
comprehensions *inline*. But, just to confuse us, 2.7 adds the new
set/dict comprehensions compiled as functions (doing it 'right' didn't
break backward compatibility).

2.7.3:

    >>> [x for x in [1]]
    [1]
    >>> x
    1

    >>> {y for y in [1]}
    set([1])
    >>> y
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    NameError: name 'y' is not defined


More information about the Tutor mailing list