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.