Looking for something that would allow skipping multiple for
loops while also having current index
available.
In pseudo code, is would look something like this:
z = [1,2,3,4,5,6,7,8]
for element in z:
<calculations that need index>
skip(3 iterations) if element == 5
Is there such a thing in Python 2?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With