4

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?

2 Answers 2

6

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
2
  • 1
    generating a "trash" list doesnt look the best option I think. Maybe consume it wih a simple loop? for _ in xrange(3): next(z), btw, no need to use iter, because islice behaves like an iterator already
    – Netwave
    Commented Dec 5, 2018 at 12:15
  • 1
    I like this answer, but would reverse the order. next first, list(islice(...)) as an educational alternative.
    – jpp
    Commented Dec 5, 2018 at 12:19
3

You can use a while loop for this purpose.

z = [1,2,3,4,5,6,7,8]
i = 0

while i < len(z):
    # ... calculations that need index
    if i == 5:
        i += 3
        continue

    i += 1
3
  • 1
    This doesn't actually skip loop iterations.
    – cs95
    Commented Dec 5, 2018 at 12:08
  • Okay, that looks good. Btw, I did not downvote you, but I hope the downvoter sees this and reverses it.
    – cs95
    Commented Dec 5, 2018 at 12:20
  • 1
    Hmm, one more suggestion, you may end up skipping an extra iteration by mistake, so take a look at that again.
    – cs95
    Commented Dec 5, 2018 at 12:20

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.