Is there a robust, universal way in python to skip first element in the for
loop?
The only way I can think of is to write a special generator by hand:
def skipFirst( it ):
it = iter(it) #identity for iterators
it.next()
for x in it:
yield x
And use it for example like:
for x in skipFirst(anIterable):
print repr(x)
and like:
doStuff( str(x) for x in skipFirst(anIterable) )
and like:
[ x for x in skipFirst(anIterable) if x is not None ]
I know we can do slices on lists (x for x in aList[1:])
but this makes a copy and does not work for all sequences, iterators, collections etc.
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.
The continue statement (with or without a label reference) can only be used to skip one loop iteration. The break statement, without a label reference, can only be used to jump out of a loop or a switch.
You can start a loop at whatever you want. The reason you see loops starting at zero often, is because they are looping through an array. Since the first item in an array is at index '0', it makes sense to start looping from 0 to access every item in an array. Save this answer.
The Python break statement immediately terminates a loop entirely. Program execution proceeds to the first statement following the loop body. The Python continue statement immediately terminates the current loop iteration.
When skipping just one item, I'd use the next()
function:
it = iter(iterable_or_sequence)
next(it, None) # skip first item.
for elem in it:
# all but the first element
By giving it a second argument, a default value, it'll also swallow the StopIteration
exception. It doesn't require an import, can simplify a cluttered for
loop setup, and can be used in a for
loop to conditionally skip items.
If you were expecting to iterate over all elements of it
skipping the first item, then itertools.islice()
is appropriate:
from itertools import islice
for elem in islice(it, 1, None):
# all but the first element
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