In python, iterator in for loop couldn’t be changed.
example:
b = range(10)
print b
##
for i in b:
i += i
print b
##use list comprehensions!!!
for i, num in enumerate(b):
b[i] = num + 1
print b
##
b = [i+1 for i in b]
print b
output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
Acutally, we shouldn’t change the object when iterating it.
Exmaple:
myDict = {'a':1, 'b':2, 'c':3, 'd':4}
for eachKey in myDict:
print eachKey, myDict[eachKey]
del myDict[eachKey]
output:
a 1
RuntimeError: dictionary changed size during iteration