Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skip multiple iterations in a loop

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?

like image 683
Igor Avatar asked Jan 02 '23 13:01

Igor


1 Answers

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 listifying 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
like image 171
cs95 Avatar answered Jan 04 '23 04:01

cs95