The for loop assigns a new value i each iteration of the loop, namely the next value taken from the iterable loop (in this case, range(16) .
You can change i in the loop itself, but that will not change the iterative for .
If you want to change the iterable loop, then you will need to do it directly on iterable:
loop_iterable = iter(range(16)) for i in loop_iterable: if i == 0: for j in range(8): print 'i is (if) ' + str(i) i = next(loop_iterable) else: print 'i is (else)' + str(i)
Here we create an iterator object from the range(10) sequence using iter() ; the for statement does the same under the hood, but now we can directly access the iterator. The next() function advances the iterator to the next value, as a for loop would do.
However, the easiest way is to use a while :
i = 0 while i < 16: if i == 0: for j in range(8): print 'i is (if) ' + str(i) i = next(loop_iterable) else: print 'i is (else)' + str(i) i += 1
Keep in mind that the Python for loop statement is not like a C loop or Java or JavaScript for loop. Instead, it is a Foreach loop . range() simply generates a sequence of numbers for the loop, as opposed to a C-style for loop, which combines the initial assignment ( i = 0 ), test ( i < 16) ) and the loop increment ( i += 1 ) into one statement.
source share