How to skip first element in `for` loop?
for i in list1[1:]: #Skip first element
# Do What Ever you want
Explanation:
When you use [1:] in for loop list it skips the first element and start loop from second element to last element
I think itertools.islice
will do the trick:
islice( anIterable, 1, None )
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