for x in... x remains global

skip at pobox.com skip at pobox.com
Wed Nov 8 15:23:31 CET 2006


    Diez> It's an somewhat unfortunate fact that loop variables leak to the
    Diez> outer scope.  List-comps as well, btw.

It's unfortunate that loop variables leak from list comprehensions (they
don't leak in genexps).  It's by design in for loops though.  Consider:

    for i in range(10):
        if i*i == 9:
            break
    print i

In this silly example, the loop index is the useful value of the
computation.  You could assign to a different variable, though that would be
slightly ugly:

    for i in range(10:
        j = i
        if j*j == 9:
            break
    print j

Skip



More information about the Python-list mailing list