Python doesn't have a concept similar to block scoping that would narrow the lifetime of i
to the for
loop that defines it; all local variables are scoped to the entire function, and persist until the function is complete (del
can unbind the name from the value, but if you reassign it, it's assigned to the same storage location)1.
After the for
loop completes, i
just has whatever was iterated last (the last thing in the sequence in this case, though use of break
within the loop could lead to it being an earlier value), and keeps it until you reassign it or the function completes (by exception or return
, implicit or explicit).
1 Technically, CPython 3.x does automatically unbind caught exceptions after the exception handling completes, to avoid cyclic references delaying object cleanup. This behaves a little like block scoping, but it's equivalent to the explicit del
case; the name continues to exist, it's just not bound to any object.