What's the best way of skip N values of the iteration variable in Python?
Use continue
.
for i in xrange(value):
if condition:
continue
If you want to force your iterable to skip forwards, you must call .next()
.
>>> iterable = iter(xrange(100))
>>> for i in iterable:
... if i % 10 == 0:
... [iterable.next() for x in range(10)]
...
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[21, 22, 23, 24, 25, 26, 27, 28, 29, 30]
[41, 42, 43, 44, 45, 46, 47, 48, 49, 50]
[61, 62, 63, 64, 65, 66, 67, 68, 69, 70]
[81, 82, 83, 84, 85, 86, 87, 88, 89, 90]
As you can see, this is disgusting.
Create the iterable before the loop.
Skip one by using next on the iterator
it = iter(xrange(value))
for i in it:
if condition:
i = next(it)
Skip many by using itertools or recipes based on ideas from itertools.
itertools.dropwhile()
it = iter(xrange(value))
for i in it:
if x<5:
i = dropwhile(lambda x: x<5, it)
Take a read through the itertools page, it shows some very common uses of working with iterators.
itertools islice
it = islice(xrange(value), 10)
for i in it:
...do stuff with i...
Itertools has a recommended way to do this: https://docs.python.org/3.7/library/itertools.html#itertools-recipes
import collections
def tail(n, iterable):
"Return an iterator over the last n items"
# tail(3, 'ABCDEFG') --> E F G
return iter(collections.deque(iterable, maxlen=n))
Now you can do:
for i in tail(5, range(10)):
print(i)
to get
5
6
7
8
9