how to increment the iterator from inside for loop in python 3?
Save a copy of the iterator as a named object. Then you can skip ahead if you want to.
>>> myiter = iter(range(0, 10))>>> for i in myiter: print(i) next(myiter, None)...02468
You can't do that inside a for
loop. Because every time that the loop gets restarted it reassign the variable i
(even after you change it inside the loop) and every time you just increase the reassigned variable. If you want to do such thing you better to use a while
loop and increase the throwaway variable manually.
>>> i=0>>> while i< 10 :... print(i)... i +=2... print("increased i", i)... 0('increased i', 2)2('increased i', 4)4('increased i', 6)6('increased i', 8)8('increased i', 10)
Beside that, if you want to increase the variable on a period rather than based some particular condition, you can use a proper slicers to slice the iterable in which you're looping over.
For instance if you have an iterator you can use itertools.islice()
if you have a list you can simply use steps while indexing (my_list[start:end:step]
).
range()
has an optional third parameter to specify the step. Use that to increment the counter by two. For example:
for i in range(0, 10, 2): print(i) print("increased i", i)
The reason that you cannot increment i
like a normal variable is because when the for-loop starts to execute, a list (or a range object in Python 3+) is created, and i
merely represents each value in that object incrementally.