Unexpected result.

Steven Bethard steven.bethard at gmail.com
Thu Sep 23 15:51:36 EDT 2004


Grzegorz Dostatni <grzegorz <at> ee.ualberta.ca> writes:
> My question is whether it would make more sense (be more
> intuitive) to have a for loop create its own local scope

I highly doubt you're going to convince Python to change on this, but you can 
always try...  ;)

Anyway, there are times when you want to access the loop variable afterwards, 
e.g.:

for i, line in enumerate(file(...)):
    # do something with each line of the file
print 'lines in file:', i

So the tradeoff is between catching errors like yours (and as Larry Bates 
says, you really shouldn't use the same variable in nested loops anyway) and 
being able to be more expressive.  My suspicion is that there really aren't 
too many use cases where you really need to have the same loop variable name 
in a nested for loop, but I bet there are a fair number of good use cases for 
having access to the loop variable after the end of the loop.

Steve




More information about the Python-list mailing list