Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to skip first element in `for` loop?

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.

like image 300
user2622016 Avatar asked Dec 19 '13 12:12

user2622016


People also ask

How do you skip one item in a for 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.

How do you skip a loop 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.

Does a for loop have to start at 1?

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.

How do you break the first loop in Python?

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.


1 Answers

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
like image 133
Martijn Pieters Avatar answered Sep 28 '22 04:09

Martijn Pieters