Search code examples
pythonpython-2.7language-designpython-2.x

How to avoid leaking the loop index into namespace for python 2.x?


for i in mylist:
    process(i)

[process(j) for j in mylist]

At the end of the execution, i and j remain in the namespace with the last value of mylist.

Other than creating a specialized function to hide i from leaking; what are other ways to hide loop indexes ?


Solution

  • there is not much else you can do except explicitly deleting i and j:

    for i in mylist:
        process(i)
    
    [process(j) for j in mylist]
    
    print j, i  # -> 8 8
    del i, j
    print j, i  # NameError: name 'j' is not defined
    

    a side note: if the list is empty, the variable remains undefined:

    for i in []:
        pass
    print i  # NameError: name 'i' is not defined
    

    and one more thing: in python 2.x variables from list-comprehensions (not generator expressions though) are leaked as well; in python 3.x this is a NameError.

    [i for i in range(3)]
    print i  #  2