Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way of skip N values of the iteration variable in Python?

In many languages we can do something like:

for (int i = 0; i < value; i++) {     if (condition)     {         i += 10;     } } 

How can I do the same in Python? The following (of course) does not work:

for i in xrange(value):     if condition:         i += 10 

I could do something like this:

i = 0 while i < value:   if condition:     i += 10   i += 1 

but I'm wondering if there is a more elegant (pythonic?) way of doing this in Python.

like image 392
Oscar Mederos Avatar asked Apr 01 '11 04:04

Oscar Mederos


People also ask

How do you skip multiple iterations in Python?

Using next() this way can raise a StopIteration exception, if the iterable is out of values. 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() .

How do you skip a value in Python?

In Python, you can use the optional 'step' parameter to skip numbers in a range. If you are using a range object in a loop, the 'step' parameter will allow you to skip iterations.

How do you skip iterations in the loop?

You can use the continue statement if you need to skip the current iteration of a for or while loop and move onto the next iteration.


2 Answers

Use continue.

for i in xrange(value):     if condition:         continue 

If you want to force your iterable to skip forwards, you must call .next().

>>> iterable = iter(xrange(100)) >>> for i in iterable: ...     if i % 10 == 0: ...         [iterable.next() for x in range(10)] ...  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] [21, 22, 23, 24, 25, 26, 27, 28, 29, 30] [41, 42, 43, 44, 45, 46, 47, 48, 49, 50] [61, 62, 63, 64, 65, 66, 67, 68, 69, 70] [81, 82, 83, 84, 85, 86, 87, 88, 89, 90] 

As you can see, this is disgusting.

like image 133
bradley.ayers Avatar answered Sep 17 '22 18:09

bradley.ayers


Create the iterable before the loop.

Skip one by using next on the iterator

it = iter(xrange(value)) for i in it:     if condition:         i = next(it) 

Skip many by using itertools or recipes based on ideas from itertools.

itertools.dropwhile()

it = iter(xrange(value)) for i in it:     if x<5:         i = dropwhile(lambda x: x<5, it) 

Take a read through the itertools page, it shows some very common uses of working with iterators.

itertools islice

it = islice(xrange(value), 10) for i in it:     ...do stuff with i... 
like image 27
kevpie Avatar answered Sep 18 '22 18:09

kevpie