In python I usually loop through ranges simply by
for i in range(100):
#do something
but now I want to skip a few steps in the loop. Mo
You cannot alter the target list (i
in this case) of a for
loop. Use a while
loop instead:
while i < 10:
i += 1
if i == 2:
i += 3
Alternatively, use an iterable and increment that:
from itertools import islice
numbers = iter(range(10))
for i in numbers:
if i == 2:
next(islice(numbers, 3, 3), None) # consume 3
By assigning the result of iter()
to a local variable, we can advance the loop sequence inside the loop using standard iteration tools (next()
, or here, a shortened version of the itertools
consume recipe). for
normally calls iter()
for us when looping over a iterator.