I\'m not asking about Python\'s scoping rules; I understand generally how scoping works in Python for loops. My question is why the design decisions were m
A really useful case for this is when using enumerate
and you want the total count in the end:
for count, x in enumerate(someiterator, start=1):
dosomething(count, x)
print "I did something {0} times".format(count)
Is this necessary? No. But, it sure is convenient.
Another thing to be aware of: in Python 2, variables in list comprehensions are leaked as well:
>>> [x**2 for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> x
9
But, the same does not apply to Python 3.