Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't Python delete the iterate variable after a loop? [duplicate]

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.

like image 500
zfz Avatar asked May 25 '13 08:05

zfz


Video Answer


1 Answers

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.

like image 148
Martijn Pieters Avatar answered Oct 20 '22 07:10

Martijn Pieters