isPrime works but UnBoundLocalError when mapping on list

Terry Reedy tjreedy at
Thu Jul 17 01:46:44 CEST 2008

Andreas Tawn wrote:
> Terry Reedy wrote:

>> For loop variables continue after the loop exits.  This is 
>> intentional.
> I never knew that and I can't find reference to it in the docs. Can you
> help me with the reasons for it?

1. Python's reluctance to multiply scopes without necessity (as other 
respondents have discussed).

2. This way, a for loop abbreviates an equivalent while loop (which does 
have an explicit assignment).  Something like:

for item in iterable:

it = iter(iterable)
while True
   item = next(it) # 3.0, 2.6?

Of course, one could add 'del item' after the loop, but...

3. For search loops, the final value bound may be wanted after the loop.

for item in iterable:
   if pred(item): break
   item = default
# item is now first item in iterable with property pred
# or fallback default.


More information about the Python-list mailing list