Skip Multiple Iterations in Loop

Skip multiple iterations in loop

for uses iter(song) to loop; you can do this in your own code and then advance the iterator inside the loop; calling iter() on the iterable again will only return the same iterable object so you can advance the iterable inside the loop with for following right along in the next iteration.

Advance the iterator with the next() function; it works correctly in both Python 2 and 3 without having to adjust syntax:

song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life']
song_iter = iter(song)
for sing in song_iter:
print sing
if sing == 'look':
next(song_iter)
next(song_iter)
next(song_iter)
print 'a' + next(song_iter)

By moving the print sing line up we can avoid repeating ourselves too.

Using next() this way can raise a StopIteration exception, if the iterable is out of values.

You could catch that exception, but it'd be easier to give next() a second argument, a default value to ignore the exception and return the default instead:

song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life']
song_iter = iter(song)
for sing in song_iter:
print sing
if sing == 'look':
next(song_iter, None)
next(song_iter, None)
next(song_iter, None)
print 'a' + next(song_iter, '')

I'd use itertools.islice() to skip 3 elements instead; saves repeated next() calls:

from itertools import islice

song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life']
song_iter = iter(song)
for sing in song_iter:
print sing
if sing == 'look':
print 'a' + next(islice(song_iter, 3, 4), '')

The islice(song_iter, 3, 4) iterable will skip 3 elements, then return the 4th, then be done. Calling next() on that object thus retrieves the 4th element from song_iter().

Demo:

>>> from itertools import islice
>>> song = ['always', 'look', 'on', 'the', 'bright', 'side', 'of', 'life']
>>> song_iter = iter(song)
>>> for sing in song_iter:
... print sing
... if sing == 'look':
... print 'a' + next(islice(song_iter, 3, 4), '')
...
always
look
aside
of
life

Skip multiple iterations in a loop

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

Skip two or more than two iterations in a for loop

Use iterator function iter(numbers) and function next(). They are all built-in.

numbers_to_skip = [237, 360, 263, 980] 
numbers_iter = iter(numbers)
for number in numbers_iter:
if number in numbers_to_skip:
next(numbers_iter)
continue
print(number)

Skipping several iterations of for-loop based on condition

It's not just bad practice to increment the counter inside the loop in R. It simply will not work. That's not the way the language is built. If you want to get 1 and 4 printed then try:

for(i in seq(1,10,by=3) ){
if(i %in% c(1,2,3,4,5)){
print(i)
}
}

Do also note that for-loops actually return NULL. There would be a side-effect of printing to the console, but no values of variables would change. If you want values to change you need to do assignment inside the loop.

The is a next control statement:

for(i in seq(1,10) ){
if( !(i %in% c(1,4)) ){ next }
print(i)
}

How do I skip a few iterations in a for loop

You cannot alter the target list (i in this case) of a for loop. Use a while loop instead:

while i < 10:
i += 1
if i == 2:
i += 3

Alternatively, use an iterable and increment that:

from itertools import islice

numbers = iter(range(10))
for i in numbers:
if i == 2:
next(islice(numbers, 3, 3), None) # consume 3

By assigning the result of iter() to a local variable, we can advance the loop sequence inside the loop using standard iteration tools (next(), or here, a shortened version of the itertools consume recipe). for normally calls iter() for us when looping over a iterator.

C++ how to skip next 2 iterations of loop i.e. multiple continue

Consider using for loop with index:

for (size_t i = 0; i < args.size(); i++)
{
if (args[i] == "condition") {
i++;
continue;
}
}

How to skip few iterations in a for loop based on a if condition?

Skipping 4 steps after each meeting condition ((i % 300) == 0) is equal to skipping 0, 1, 2, and 3. You can simply change the condition to skip all these steps with (i % 300) < 4.

for i in range(0, 200000):
# (when 0 % 300 it meets this criteria)
if (i % 300) < 4: # Skips iteration when remainder satisfier condition
#if (i % 300) in (0,1,2,3): # or alternative skip condition
# whenever this condition is met skip 4 iterations forward
# now skip 4 iterations --- > (0, 1, 2, 3)
continue

# now continue from 4th iteration
print(i)


Related Topics



Leave a reply



Submit