I'd iterate over iter(z)
, using islice
to send unwanted elements into oblivion... ex;
from itertools import islice
z = iter([1, 2, 3, 4, 5, 6, 7, 8])
for el in z:
print(el)
if el == 4:
_ = list(islice(z, 3)) # Skip the next 3 iterations.
# 1
# 2
# 3
# 4
# 8
Optimization
If you're skipping maaaaaaany iterations, then at that point list
ifying the result will become memory inefficient. Try iteratively consuming z
:
for el in z:
print(el)
if el == 4:
for _ in xrange(3): # Skip the next 3 iterations.
next(z)
Thanks to @Netwave for the suggestion.
If you want the index too, consider wrapping iter
around an enumerate(z)
call (for python2.7.... for python-3.x, the iter
is not needed).
z = iter(enumerate([1, 2, 3, 4, 5, 6, 7, 8]))
for (idx, el) in z:
print(el)
if el == 4:
_ = list(islice(z, 3)) # Skip the next 3 iterations.
# 1
# 2
# 3
# 4
# 8