5

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.

Henrik Andersson
  • 41,844
  • 15
  • 95
  • 89
zfz
  • 1,537
  • 1
  • 21
  • 44

1 Answers1

14

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.

Community
  • 1
  • 1
Martijn Pieters
  • 963,270
  • 265
  • 3,804
  • 3,187