Fix Python – Scoping in Python ‘for’ loops


Asked By – chimeracoder

I’m not asking about Python’s scoping rules; I understand generally how scoping works in Python for loops. My question is why the design decisions were made in this way. For example (no pun intended):

for foo in xrange(10):
    bar = 2
print(foo, bar)

The above will print (9,2).

This strikes me as weird: ‘foo’ is really just controlling the loop, and ‘bar’ was defined inside the loop. I can understand why it might be necessary for ‘bar’ to be accessible outside the loop (otherwise, for loops would have very limited functionality). What I don’t understand is why it is necessary for the control variable to remain in scope after the loop exits. In my experience, it simply clutters the global namespace and makes it harder to track down errors that would be caught by interpreters in other languages.

Now we will see solution for issue: Scoping in Python ‘for’ loops


The likeliest answer is that it just keeps the grammar simple, hasn’t been a stumbling block for adoption, and many have been happy with not having to disambiguate the scope to which a name belongs when assigning to it within a loop construct. Variables are not declared within a scope, it is implied by the location of assignment statements. The global keyword exists just for this reason (to signify that assignment is done at a global scope).


Here’s a good discussion on the topic:

Previous proposals to make for-loop
variables local to the loop have
stumbled on the problem of existing
code that relies on the loop variable
keeping its value after exiting the
loop, and it seems that this is
regarded as a desirable feature.

In short, you can probably blame it on the Python community 😛

This question is answered By – Jeremy Brown

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0