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
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.
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.
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 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.
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.")
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With