Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skip iterations in enumerated list object (python)

Tags:

python

loops

skip

I have the code

for iline, line in enumerate(lines):
    ...
    if <condition>:
        <skip 5 iterations>

I would like, as you can read, have the for loop skip 5 iterations if the condition is met. I can be sure that, if the condition is met, there are 5 or more objects left in the "lines" object.

lines exists of an array of dictionaries, which have to be looped over in order

like image 705
pidgey Avatar asked Jan 25 '15 16:01

pidgey


People also ask

How do you skip iterations in Python?

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.

How do you skip a loop twice in Python?

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. The islice(song_iter, 3, 4) iterable will skip 3 elements, then return the 4th, then be done.

Is range or enumerate faster?

enumerate is faster when you want to repeatedly access the list items at their index. When you just want a list of indices, it is faster to to use len() and range/xrange.

What is enumerate () Python?

What does enumerate do in Python? The enumerate function in Python converts a data collection object into an enumerate object. Enumerate returns an object that contains a counter as a key for each value within an object, making items within the collection easier to access.


1 Answers

Using the enumeration index

Similar to the accepted answer… except without using itertools (IMHO islice doesn't improve readability), plus enumerate() already returns an iterator so you don't need the iter() at all:

lines = [{str(x): x} for x in range(20)]  # dummy data

it = enumerate(lines)
for i, line in it:
    print(line)

    if i == 10:  # condition using enumeration index
        [next(it, None) for _ in range(5)]  # skip 5

That last line can optionally be expanded for readability:

        for _ in range(5):  # skip 5
            next(it, None)

The None argument in next() avoids an exception if there aren't enough items to skip. (For the original question, it can be omitted as the OP wrote: "I can be sure that, if the condition is met, there are 5 or more objects left in the lines object.")

Not using the enumeration index

If the skip condition isn't based on the enumeration index, simply treat the list as a FIFO queue and consume from it using pop():

lines = [{str(x): x} for x in range(20)]  # dummy data

while lines:
    line = lines.pop(0)  # get first item
    print(line)

    if <condition>:  # some other kind of condition
        [lines.pop(0) for _ in range(5)]  # skip 5

As before, that last line can optionally be expanded for readability:

        for _ in range(5):  # skip 5
            lines.pop(0)

(For large lists, use collections.deque for performance.)

like image 194
jrc Avatar answered Nov 15 '22 18:11

jrc