I found the situation when running ipython. The version of python is 2.6.6 and ipython 0.13. For example:
In [1]: for i in range(100):
...: pass
...:
In [2]: who
Out [2]: i
In [3]: print i
Out [3]: 99
After the loop, the variable i
still exists. So I want to know is this a bug of Python design? If not, why? Thanks.
It is not a bug.
The for
loop does not create a new scope. Only functions and modules introduce a new scope, with classes, list/dict/set comprehensions*, lambdas and generators being specialized functions when it comes to scoping.
This is documented in the for
loop statement documentation:
The target list is not deleted when the loop is finished, but if the sequence is empty, it will not have been assigned to at all by the loop.
A practical use of this feature is getting the last item of an iterable:
last = defaultvalue
for last in my_iter:
pass
* List comprehensions in Python 2 work like for
loops, no new scope, but in Python 3 they, as well as dict and set comprehensions across Python versions, do create a new scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With